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");
This question is related to
javascript
html
dom
You can use querySelectorAll
:
document.querySelectorAll('span[property=name]');
You can get attribute using javascript,
element.getAttribute(attributeName);
Ex:
var wrap = document.getElementById("wrap");
var myattr = wrap.getAttribute("title");
Refer:
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;
}
With prototypejs :
$$('span[property=v.name]');
or
document.body.select('span[property=v.name]');
Both return an array
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'
)
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
In jQuery this is so:
$("span['property'=v:name]"); // for selecting your span element
Source: Stackoverflow.com