Check if Data Attribute Exists using Javascript

In this tutorial, you will learn how to check if a data attribute exists in javascript. Using javascript we can do anything in dom element. Getting the object attribute or a div, span, a, button etc any element attribute we use the javascript hasAttribute() method.

If the attribute is find then this methods return true other return false. Lets check how to use the JavaScript hasAttribute() to check if an element has an attribute.


To check an element has a specified attribute or not, you use the hasAttribute() method. The hasAttribute() method accepts an argument that specifies the name of the attribute that you want to check.

const result = element.hasAttribute(name);

Your Div Element

Here the element span where the attribute is title and we check the title is exits in span element or not.

  <span id="checkAttribute" title="attribute-titile">Send</span>

Example 1:

The following example uses the hasAttribute() method to check if the title attribute exists on the span element…

let element = document.querySelector('#checkAttribute');
let isAttribute = element.hasAttribute('title');
console.log(isAttribute); //true

Example 2:

<a class="has-attribute" data-method="test to get attribute">Get this element attribute</a>

    const link = document.querySelector('a');
    const result = link.hasAttribute('data-method');

Full Example:

See the following example if hasAttribute() get the attribute then returns a Boolean value true or false that indicates if the element has the specified attribute.

<!DOCTYPE html>
    <meta charset="utf-8">
    <title>JS hasAttribute() Demo</title>

    <div class="has-attribute" title="test attribute">Get this element attribute</div>

        let element = document.querySelector('.has-attribute');
        let isAttribute = element.hasAttribute('title');
        console.log(isAttribute); //true

So Use the hasAttribute() method to check if an element contains a specified attribute.

1 thought on “Check if Data Attribute Exists using Javascript”

Leave a Comment