Getting HTML elements by their attribute names

JavascriptHtmlDom

Javascript Problem Overview


There are methods available in JavaScript to get HTML elements using their ID, Class and Tag.

document.getElementByID(*id*);
document.getElementsByClassName(*class*);
document.getElementsByTagName(*tag*);

Is there any method available to get the elements according to the attribute name.

EX:

<span property="v:name">Basil Grilled Tomatoes and Onions</span>

Like:

document.getElementsByAttributeName("property");

Javascript Solutions


Solution 1 - Javascript

Yes, the function is querySelectorAll (or querySelector for a single element), which allows you to use CSS selectors to find elements.

document.querySelectorAll('[property]'); // All with attribute named "property"
document.querySelectorAll('[property="value"]'); // All with "property" set to "value" exactly.

(Complete list of attribute selectors on MDN.)

This finds all elements with the attribute property. It would be better to specify a tag name if possible:

document.querySelectorAll('span[property]');

You can work around this if necessary by looping through all the elements on the page to see whether they have the attribute set:

var withProperty = [],
    els = document.getElementsByTagName('span'), // or '*' for all types of element
    i = 0;

for (i = 0; i < els.length; i++) {
    if (els[i].hasAttribute('property')) {
        withProperty.push(els[i]);
    }
}

Libraries such as jQuery handle this for you; it's probably a good idea to let them do the heavy lifting.

For anyone dealing with ancient browsers, note that querySelectorAll was introduced to Internet Explorer in v8 (2009) and fully supported in IE9. All modern browsers support it.

Solution 2 - Javascript

In jQuery this is so:

$("span['property'=v:name]"); // for selecting your span element

Solution 3 - Javascript

Just another answer

Array.prototype.filter.call(
    document.getElementsByTagName('span'),
    function(el) {return el.getAttribute('property') == 'v.name';}
);

In future

Array.prototype.filter.call(
    document.getElementsByTagName('span'),
    (el) => el.getAttribute('property') == 'v.name'
)
3rd party edit

Intro

  • The call() method calls a function with a given this value and arguments provided individually.

  • The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Given this html markup

<span property="a">apple - no match</span>
<span property="v:name">onion - match</span>
<span property="b">root - match</span>
<span property="v:name">tomato - match</span>
<br />
<button onclick="findSpan()">find span</button>

you can use this javascript

function findSpan(){

    var spans = document.getElementsByTagName('span');
    var spansV = Array.prototype.filter.call(
         spans,
         function(el) {return el.getAttribute('property') == 'v:name';}
    );
    return spansV;
}

See demo

Solution 4 - Javascript

You can use querySelectorAll:

    document.querySelectorAll('span[property=name]');

Solution 5 - Javascript

Let's assume that you have an input:

         <input type='text' name='from'/>
  

then you can access it as follow:

        document.querySelector('input[name="from"]')

Solution 6 - Javascript

I think you want to take a look at jQuery since that Javascript library provides a lot of functionality you might want to use in this kind of cases. In your case you could write (or find one on the internet) a hasAttribute method, like so (not tested):

$.fn.hasAttribute = function(tagName, attrName){
  var result = [];
  $.each($(tagName), function(index, value) { 
     var attr = $(this).attr(attrName); 
     if (typeof attr !== 'undefined' && attr !== false)
        result.push($(this));
  });
  return result;
}

Solution 7 - Javascript

You can get attribute using javascript,

element.getAttribute(attributeName);

Ex:

var wrap = document.getElementById("wrap");
var myattr = wrap.getAttribute("title");

Refer:

https://developer.mozilla.org/en/DOM/element.getAttribute

Solution 8 - Javascript

With prototypejs :

 $$('span[property=v.name]');

or

document.body.select('span[property=v.name]');

Both return an array

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaurabh SaxenaView Question on Stackoverflow
Solution 1 - JavascriptlonesomedayView Answer on Stackoverflow
Solution 2 - JavascriptIceManView Answer on Stackoverflow
Solution 3 - JavascriptFabio MontefuscoloView Answer on Stackoverflow
Solution 4 - JavascriptPaula FleckView Answer on Stackoverflow
Solution 5 - Javascriptmohanad waloView Answer on Stackoverflow
Solution 6 - JavascriptBas SlagterView Answer on Stackoverflow
Solution 7 - JavascriptgtamilView Answer on Stackoverflow
Solution 8 - JavascriptAlain BeauvoisView Answer on Stackoverflow