JAVA SCRIPT - Finding All Elements That Share an Attribute

Finding All Elements That Share an Attribute


You want to find all elements in a web document that share the same attribute. 


Use the universal selector (*) in combination with the attribute selector to find all ele‐ ments that have an attribute, regardless of its value:

var elems = document.querySelectorAll('*[class]');

The universal selector can also be used to find all elements with an attribute that’s as‐ signed the same value:

elems = document.querySelectorAll('*[class="red"]');


The solution demonstrates a rather elegant query selector, the universal selector(*). The universal selector evaluates all elements, so it’s the one you want to use when you need to verify something about each element. In the solution, we want to find all of the ele‐ ments with a given attribute. To test whether an attribute exists, all you need to do is list the attribute name within square brackets ([attrname]). In the solution, we’re first testing whether the element contains the class attribute. If it does, it’s returned with the element collection:

var elems = document.querySelectorAll('*[class]');

+Next, we’re getting all elements with a class attribute value of red. If you’re not sure of the class name, you can use the substring-matching query selector:

var elements = document.querySelectorAll('*[class*="red"]');


Post a Comment