Languages
[Edit]
EN

JavaScript - check if element / node has attribute

0 points
Created by:
Nathanial-Donald
554

In this article, we would like to show you how to check if element / node has the attribute in JavaScript.

Quick solution:

var myElement = document.querySelector('#element-id');  // get element by id

myElement.hasAttribute(attributeName);  // check if element has the attribute

 

Practical example

In this example, we will check if myDiv element has class and onclick attributes using hasAttribute() method.

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
  <head>
    <style>
      .blue {
        background: lightblue;
      }
    </style>
  </head>
  <body>
    <div id="my-div" class="blue">This is my div.</div>
    <script>
      var myDiv = document.querySelector('#my-div');    // get element by id
      var classCheck = myDiv.hasAttribute('class');     // check if myDiv has class attribute
      var onclickCheck = myDiv.hasAttribute('onclick'); // check if myDiv has onclick attribute
      console.log(classCheck);    // true
      console.log(onclickCheck);  // false
    </script>
  </body>
</html>

Alternative titles

  1. JavaScript - check if element / node attribute exists
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join