Get Off My Lawn
Get Off My Lawn

Reputation: 36289

Get html nodes that are not within a node with attribute X

I have the following xpath query, and I am not sure how to make it so it only finds items with the attribute pi-repeat, but not it's children that have that attribute.

$xpath = new DOMXPath($dom);
foreach ($xpath->query('//*[@pi-repeat]') as $node) {
    // Do stuff
}

Html example:

<body>
    <div pi-repeat="thing1">
        <div pi-repeat="sub-item"></div>
    </div>
    <div class="a-class">
        <div pi-repeat="thing2">
            <div pi-repeat="sub-item"></div>
        </div>
    </div>
</body>

As you can see here there are four pi-repeat attributes, I would like my query to only select the ones that are not within an element pi-repeat attribute.

In this case, only thing1 and thing2 would get selected.

Upvotes: 1

Views: 33

Answers (1)

har07
har07

Reputation: 89285

The 2nd predicate in the XPath below will do the job. It filters out elements where ancestor element has pi-repeat attribute :

//*[@pi-repeat][not(ancestor::*[@pi-repeat])]

Upvotes: 3

Related Questions