JS hasAttribute with data attribute value
Asked Answered
A

5

8

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:

document.hasAttribute('data-mod');

but this will be false:

document.hasAttribute('data-mod="do"')

Is there any way to natively check for a data attribute on a DOM element with the value?

Abbess answered 4/3, 2016 at 21:32 Comment(3)
document doesn't have attributes. Do you mean an element in the document, or a specific element has an attribute?Titustityus
Make your question clearer.Primateship
"Is there a native way, no JQuery," Why do you have jquery tag at Question ?Weakkneed
T
16

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') {
    ...
}
Tunnage answered 4/3, 2016 at 21:35 Comment(2)
matches worked for my use case. What are the implications/ways to support older browsers? if i remember some defined it under different names like msMatchesSelctor() right?Abbess
For the most up-to-date compatibility information, I recommend consulting caniuse, which shows that you'd need to use msMatchesSelector as a fallback to have IE9+ support.Tunnage
P
3

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.

Pelletier answered 4/3, 2016 at 21:37 Comment(7)
Sorry I should have been clearer. I do not know what the data attribute or the value will be within the function because it can changeAbbess
@Abbess So you will have only this 'data-mod="do"' during the execution?Pelletier
The function will take in a selector param. its contents could be any valid selector including any data-*="" I need to be able to see if the element has that selector.Abbess
@Abbess You can go with element.matches(selector) as suggested by zzzzBov for your case. But careful while using it as it is being supported by recent browsers only. developer.mozilla.org/en-US/docs/Web/API/Element/matchesPelletier
Yea i noticed that will match my use case best. Do you know what kind of support for ie 10+? I saw they just define them under different names so if i checked for all the possible names (mozMatchesSelector, webkitMatchesSelector, etc) would I be fine support wise?Abbess
@guest27314 We arent discussing element.dataset but thank youAbbess
Can also be written in dot notation like so: element.dataset.mod === 'do'.Gauldin
D
2

Yes, here it goes:

var selector = document.getElementsByTagName("H1")[0]; //Example of an h1
if (selector.getAttribute('data-mod') == "do"){
  //Do your logic
}
Decagram answered 4/3, 2016 at 21:35 Comment(3)
TypeError: document.getAttribute is not a functionTitustityus
sorry, document won't have attribute, you have to select a valid selectorDecagram
Thank's, sure it works fine. console.log(document.querySelector('#input-number').getAttribute('type')=='number');Towery
O
0

This may work...

var list = document.querySelectorAll('[data-mod="do"]');
Obolus answered 4/3, 2016 at 21:46 Comment(0)
W
0

You could use Element.attributes

function data(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) {
          return true
        }
        return true
      } else {
        return true
      }
    }
  }
  return false
}

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))
<div data="abc">abc</div>
<div id="prop" data-prop="123">123</div>
<div>no data</div>
Weakkneed answered 4/3, 2016 at 21:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.