Jey
Jey

Reputation: 1511

Javascript to get elements by their attributes

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

Here is a sample html page.. I need to select the html elements by its attributes i can get the attribute values by getAttribute() but i need to select all the elements first.

How in javascript to get elements which has the attribute name as "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.

Upvotes: 10

Views: 27923

Answers (6)

RedPoppy
RedPoppy

Reputation: 623

In new browsers you can do:

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

Upvotes: 23

Irvin Dominin
Irvin Dominin

Reputation: 30993

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

You can give a try to a working fiddle: http://jsfiddle.net/Yx7EU/

Hope this can help.

Upvotes: 0

david
david

Reputation: 4278

store each element in a array the loop throught 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"));
   }
}

Upvotes: 6

Philipp Kyeck
Philipp Kyeck

Reputation: 18820

you can use

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

but this also returns the html, head and body ...

and then do a loop over all elements and look for the attributes.

Upvotes: 0

Romi Halasz
Romi Halasz

Reputation: 2009

You can select elements by tag name using document.body.getElementsByTagName("div") to get all the div elements inside your document. This function returns an array of elements, which you can parse and filter out elements that don't match your criteria.

Upvotes: 1

I need an IPhone.
I need an IPhone.

Reputation: 11

You can traver all elements of DOM tree.

Upvotes: 0

Related Questions