Skip to content

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.


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



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

hasAttribute Examples

Example 1


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


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



Example 2


<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>

function myFunction() {
  var x = document.getElementById("myBtn").hasAttribute("onclick");
  document.getElementById("demo").innerHTML = x;



Leave a Reply

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

You are commenting using your 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: