Js Hasattribute With Data Attribute Value
Is there a native way, no jQuery, to check if a dom element has the attribute with the selected value. For example: //assume doc has data-mod='do' defined This will be true: docu
Solution 1:
You have to access the attribute's value via getAttribute
and compare it to your expected string:
if (node.getAttribute('data-mod') === 'do') {
...
}
For modern browsers you can use matches
:
if (node.matches('[data-mod="do"]')) {
...
}
… or for [data-*]
attributes you can use dataset
:
if (node.dataset.mod === 'do') {
...
}
Solution 2:
You can do it properly with dataset
,
if (elementNode.dataset['mod'] == 'do') {
//your code goes here.
}
By using dataset
you can access the data-attributes of an element easily.
Solution 3:
Yes, here it goes:
var selector = document.getElementsByTagName("H1")[0]; //Exemple of a h1if (selector.getAttribute('data-mod') == "do"){
//Do your logic
}
Solution 4:
This may work...
var list = document.querySelectorAll('[data-mod="do"]');
Solution 5:
You could use Element.attributes
functiondata(el, dataName, dataValue) {
for (var i = 0; i < el.attributes.length; i++) {
if (/^(data)(?=-\w+|=[^=]*$|=$|$)/g.test(el.attributes[i].name)) {
if (dataName && el.attributes[i].name === "data-" + dataName) {
if (dataName && dataValue
&& el.attributes[i].name === "data-" + dataName
&& el.attributes[i].value === dataValue) {
returntrue
}
returntrue
} else {
returntrue
}
}
}
returnfalse
}
var elems = document.querySelectorAll("div");
for (var i = 0; i < elems.length; i++) {
console.log(data(elems[i]))
}
var _name = "prop", _value = "123";
console.log("element #"
+ elems[1].id
+" has `data-*` attribute name:"
+_name
+", value:"+_value
, data(elems[1], _name, _value))
<divdata="abc">abc</div><divid="prop"data-prop="123">123</div><div>no data</div>
Post a Comment for "Js Hasattribute With Data Attribute Value"