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 } 
                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.
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 .
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 } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With