Check if the clicked element is a DIV or not using JavaScript

← PrevNext →

One of simplest ways to check if the clicked element is a DIV or not is by using the "tagName" property in JavaScript. The tagName property returns the tag name of the element and using this property we can check what type of element it is.
<body>
  <div>
    content inside DIV
  </div>
  <p>
    content inside P element
  </p>
</body>

<script>
    window.addEventListener('click', function (e) {
        if (e.target.tagName === 'DIV') {
            alert('Its a DIV element');
        }
    });
</script>
Try it

Related Article

How to check if the element is an IMG element using JavaScript?

I am extending the above example. Now, lets get the contents of a DIV element only, after clicking the element (using the above method).

<body>
  <div>
    inside 1st DIV...
  </div>
  <p>
    content inside P element
  </p>
  <div>
    another DIV element...
  </div>
</body>

<script>
    window.addEventListener('click', function (e) {
        if (e.target.tagName === 'DIV') {
          alert('Clicked element is DIV and its contents are... ' + e.target.innerHTML);
        }
        else {
            alert('Oh no, its not a DIV element');
        }
    });
</script>
Try it

Happy coding. 😀

← PreviousNext →