Skip to content
Advertisements

DOM hasAttribute ()

As we create HTML elements in JavaScript, we can create and delete their attributes. For this, we use the setAttribute () method to create the attribute, the removeAttribute () method to delete the attribute, the getAttribute () method to find the attribute value, and the hasAttribute () method to check the attribute.


hasAttribute

The hasAttribute () method returns true if the specified attribute exists, otherwise false.

Syntax:

element.hasAttribute(name)

name: The attribute name that you want to check if it exists.


hasAttribute Examples

Example 1

<body>

    <div class="box">
        <input class="txt" type="text" value="box list" />
        <span onclick="removeFunction()"><i class="fas fa-times"></i></span>
    </div>


    <script>

        function removeFunction() {
            let bloen = document.querySelector(".box").hasAttribute("class");
            if (bloen === true) {
                document.querySelector(".box").removeAttribute("class");
            }
            else {
                document.querySelector(".box").setAttribute("class");
            }
        }

    </script>

</body>

Example 2

<body>

<p>Click the button to find out if the button element has an onclick attribute.</p>

<button id="myBtn" onclick="myFunction()">Try it</button>

<p>Internet Explorer 8 and earlier does not support the hasAttribute() method.</p>

<p id="demo"></p>

<script>
function myFunction() {
  var x = document.getElementById("myBtn").hasAttribute("onclick");
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
Advertisements

4 Comments »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: