Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to get elements by its attribute

Tags:

javascript

<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.

like image 867
Jeyanth Kumar Avatar asked Dec 06 '11 07:12

Jeyanth Kumar


People also ask

Can we find an element using its attribute value?

Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.

How do you find element using JavaScript?

A simple way of finding this element in JavaScript would be: var myDiv = document. getElementById("myDiv"); // Would find the DIV element by its ID, which in this case is 'myDiv'.

How do I grab an element by ID?

Document.getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

Can you get element by type in JavaScript?

Use the querySelectorAll() method to get all elements by type, e.g. document. querySelectorAll('input[type="text"]') . The method returns a NodeList containing the elements that match the provided selector.


1 Answers

In new browsers you can do:

var el = document.querySelector('[someAttribute="someValue"]');
like image 103
RedPoppy Avatar answered Sep 27 '22 20:09

RedPoppy