php-html-parser icon indicating copy to clipboard operation
php-html-parser copied to clipboard

Comma separated selector doesn't return elements in DOM order

Open mishterk opened this issue 5 years ago • 1 comments

Hi there,

Great library — appreciate the effort on this.

I'm running into a small issue where the order of selectors determines the order of the returned nodes. e.g;

$dom->find( 'h1,h2,h3,h4,h5,h6' )

Unexpectedly returns all <h1> tags, then <h2> tag, and so on.

I have a document where the dom nodes are ordered such as:

<h1>
<h2>
<h3>
<h2>
<h2>

I need to get all header tags in the order they appear in the DOM but instead I'm getting h1, h2, h2, h2, h3.

Is there perhaps something I'm doing wrong on my end or is this a bug?

Cheers, Phil

mishterk avatar Jan 29 '21 03:01 mishterk

So I've just resorted to the following as a workaround in case anyone else comes across this:

$headings = $dom->find( 'h1,h2,h3,h4,h5,h6' )->toArray();
usort( $headings, function ( $a, $b ) {
    return ( $a->id() < $b->id() ) ? - 1 : 1;
} );

mishterk avatar Jan 29 '21 03:01 mishterk