How to check if data attribute exist with plain javascript?

JavascriptHtml

Javascript Problem Overview


I want to check if an HTML5 data attribute exists using plain javascript. I have tried the below code snippet, but it doesn't work.

if(object.getAttribute("data-params")==="undefined") {
   //data-attribute doesn't exist
}

Javascript Solutions


Solution 1 - Javascript

Element.getAttribute returns null or empty string if the attribute does not exist.

You'd use Element.hasAttribute:

if (!object.hasAttribute("data-example-param")) {
    // data attribute doesn't exist
}

or Element.dataset (see also: in operator):

if (!("exampleParam" in object.dataset)) {
    // data attribute doesn't exist
}

or even

if (!object.getAttribute("data-example-param")) {
    // data attribute doesn't exist or is empty
}

Solution 2 - Javascript

Checking against null also yielded the solution.

if (object.getAttribute("data-example-param") === null) {
//data attribute doesn't exist
 }else{
 //data attribute exists
 }

Solution 3 - Javascript

You could as well just use the dataset API.

HTMLElement.dataset

>The HTMLElement.dataset read-only property allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element. It is a map of DOMString, one entry for each custom data attribute.

Sadly this will not work in IE10 but i am pretty sure that there is a shim out there somewhere.

Here is an example

var containerData 	= document.querySelector('#container').dataset,
    contentData 	= document.querySelector('#content').dataset;

// Check if dataset is empty or not.
console.log(Object.keys(containerData).length === 0);
console.log(Object.keys(contentData).length === 0);

// Check for specific data
if (containerData.hasOwnProperty('bar')) {
  console.log(containerData.bar);
}

// Here is the dataset
console.log(containerData);

<div id="container" data-foo="bar" data-bar="foo">
  <div id="content">
    Content
  </div>
</div>

Solution 4 - Javascript

The code you posted doesn't won't work as you expect, what you're doing here is checking if the attribute-value of the named attribute ("data-params") is equal to "undefined", which will return true only if the attribute is data-params="undefined".

if (object.getAttribute("data-params") === "undefined") {
   // the "data-params" attribute-value is exactly "undefined"
   // note that `getAttribute()` is a 
}

What I suspect you want to do is:

var typeOfObjectAttribute = typeof object.getAttribute("data-params");

if (typeOfObjectAttribute === null || typeOfObjectAttribute === "") {
   // data-params attribute doesn't exist on that Node.
}

Note that – according Mozilla Developer Network (at the reference for Element.getAttribute(), below) – states that:

> getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string)…

It's also worth noting that getAttribute() is a method of the Element nodes, rather than generic objects.

Incidentally, you could also use the following approach (again, testing that the attribute is not set):

// here we look to see if the 'params' key is present in the
// HTMLElement.dataset object of the element, and then invert
// that result using the '!' operator, to check that the
// attribute *isn't* present:
if (!('params' in document.getElementById('elementID').dataset)) {
    // the data-params attribute is not present.
}

References:

Solution 5 - Javascript

Try using typeof:

if(typeof object.getAttribute("data-params") === "undefined") {
   console.log('data-attribute doesn't exist');
}

Solution 6 - Javascript

The only thing that worked well for me was this.

if(typeof object.dataset.sheet === "undefined") {
  console.log('Data attribute does not exist');
}

Solution 7 - Javascript

Even more simple:

if (object.dataset.sheet !== undefined) {
  // the "data-sheet" attribute exists
}

Solution 8 - Javascript

To see if a given HTML5 element has a specific custom HTML5 data-* attribute, simply examine the element's dataset.

A dataset is a DOMStringMap object so you can use the hasOwnProperty() method:

if (element.dataset.hasOwnProperty('params')) {

  [... CODE HERE...]

}

Solution 9 - Javascript

You cang do just falsy value check

if(!object.getAttribute("data-params")) {
   //data-attribute doesn't exist
}

cause getAttribute can return null or empty string

also you can use object.hasAttribute("data-params") just to check if attribute exists

Solution 10 - Javascript

If anyone landed here knowing what data attribute they are looking for then you can check if it exists with

HTML:

<input id="your-element" data-type="something">

JS:

const element = document.querySelector('#your-element');
if( element.dataset.type === 'something'){
// Do something
}

Of course the type in data-type in the example above is a custom name, data attributes can have any name such as data-cats or data-dogs etc.. ... ...

Solution 11 - Javascript

You can use the matches() method and the selector works the same way as a query selector does

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
QuestionjollykoshyView Question on Stackoverflow
Solution 1 - JavascriptvaultahView Answer on Stackoverflow
Solution 2 - JavascriptjollykoshyView Answer on Stackoverflow
Solution 3 - JavascriptDavidDomainView Answer on Stackoverflow
Solution 4 - JavascriptDavid ThomasView Answer on Stackoverflow
Solution 5 - JavascriptTobias GolbsView Answer on Stackoverflow
Solution 6 - JavascriptJens TörnellView Answer on Stackoverflow
Solution 7 - JavascriptFreddoView Answer on Stackoverflow
Solution 8 - JavascriptRounin - Standing with UkraineView Answer on Stackoverflow
Solution 9 - JavascriptAndreyView Answer on Stackoverflow
Solution 10 - JavascriptUriahs VictorView Answer on Stackoverflow
Solution 11 - JavascriptDanView Answer on Stackoverflow