How to check if data attribute exist with plain javascript?
Checking against null also yielded the solution.
if (object.getAttribute("data-example-param") === null) {
//data attribute doesn't exist
}else{
//data attribute exists
}
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
}