Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if data attribute exist with plain javascript?

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 } 
like image 681
jollykoshy Avatar asked Aug 27 '15 12:08

jollykoshy


People also ask

How do I check if an element has a data attribute?

To check if an HTML element has a specific attribute, you can use the hasAttribute() method. This method returns true if the specified attribute exists, otherwise it returns false . The hasAttribute() method also works for the HTML5 data-* attributes.

How do you check if data attribute exists in jQuery?

The jQuery. hasData() method provides a way to determine if an element currently has any values that were set using jQuery. data() . If there is no data object associated with an element, the method returns false ; otherwise it returns true .


1 Answers

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 } 
like image 141
vaultah Avatar answered Sep 17 '22 15:09

vaultah