..... ...
... ..... ... <...">

Javascript to get elements by its attribute

<body> <span someAttribute="xyz">.....</span> ... <div> ... <span someAttribute="abc">.....</span> ... <div someAttribute="pqr">.....</div> ... </div> </body> 

Here is an example html page. I need to select html elements according to its attributes, I can get the values ​​of the getAttribute() attribute, but first I need to select all the elements.

How in javascript to get elements that have an attribute name like "someAttribute". Once I get the elements, I can get the attribute values ​​and use my function.

Note. I want to do this without using jquery.

+6
source share
7 answers

store each element in an array, loop through each element, and if the element contains the attribute someAttribute do somgthing.

 var arr_elms = []; arr_elms = document.body.getElementsByTagName("*"); var elms_len = arr_elms.length; for (var i = 0; i < elms_len; i++) { if(arr_elms[i].getAttribute("someAttribute") != null){ alert("FOUND : " + arr_elms[i].getAttribute("someAttribute")); } } 
+6
source

In new browsers you can:

 var el = document.querySelector('[someAttribute="someValue"]'); 
+6
source

You can move all elements of the DOM tree.

0
source

You can select elements by tag name using document.body.getElementsByTagName("div") to get all div elements inside your document. This function returns an array of elements that you can analyze and filter out elements that do not meet your criteria.

0
source

you can use

 var all = document.getElementsByTagName('*'); 

but it also returns html , head and body ...

and then loop over all the elements and find the attributes.

0
source

I found a fragment called getElementsByAttribute(doc, tagArray, attribute, attributeValue)

You can try working on the fiddle: http://jsfiddle.net/Yx7EU/

Hope this helps.

0
source

var elem = document.querySelectorAll ('tagName [attributeName = "' + valueInVariable + '"]')

-2
source

Source: https://habr.com/ru/post/903171/


All Articles