<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.
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.
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'.
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.
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.
In new browsers you can do:
var el = document.querySelector('[someAttribute="someValue"]');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With