How to check if data attribute exist with plain 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
}

Leave a Comment