Nael El Shawwa
Nael El Shawwa

Reputation: 348

How to iterate over HTML DOM nodes that contain one of the provided attributes?

I want to be able to get the first matching element, then the second, and so on, for the following CSS selector:

[att]

The below selectors are not valid CSS3 selectors, but that is what I'm trying to accomplish:

   [att][0]
   [att][1]
   ...
   [att][n]

Can I combine multiple selectors and iterate over each matching node just like the example above?

[att1],[att2]

If this can't be done with native DOM or CSS3 selectors, then an XPath query is also an option.

Upvotes: 2

Views: 1344

Answers (2)

BoltClock
BoltClock

Reputation: 723538

If document.querySelectorAll() is an option, it will be very easy — just pass the selector and the browser will handle the rest:

var elms = document.querySelectorAll('[att]');

for (var i = 0; i < elms.length; ++i) {
    alert(elms[i].tagName);
}

It works with any CSS selector you pass it provided the browser supports it (which in this case any browser implementing the function should already do). So to pick elements that have either att1, att2 or both, use this as mentioned in the comments:

var elms = document.querySelectorAll('[att1], [att2]');

Upvotes: 4

user578895
user578895

Reputation:

Using jQuery:

$('[att]');

Also, this works:

$('[att1],[att2]');

The first will give you a list of all elements with an att attribute. If you don't want to use jQuery, your code will run much slower since the logical way to do this is:

var elems = document.getElementsByTagName('*');
for(var i=0, l=elems.length; i<l; i++){
    if(elems[i].getAttribute('att')){
        // do stuff
    }
}

The reason jQuery is actually faster is because it will use XPath queries or other methods when possible, which will greatly speed up the execution. Of course you could implement XPath in the above code if you want.

Upvotes: 1

Related Questions