JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to check if an attribute exists in JavaScript?

If you want to check whether an attribute exists with an HTML element, then use the hasAttribute() method.

The hasAttribute() method returns true if an attribute is specified with the HTML element; otherwise, it will return false.

The syntax for the hasAttribute() method is:


For example, you can check whether you have specified the image source to the img element.


<img id="logo" alt="JavaScript Logo" />

JavaScript Code

let image = document.getElementById('logo');
let imageSource = image.hasAttribute('src');
  console.log('Image source is mentioned.');
  image.setAttribute('src', '');

The hasAttribute() method allows to check if data-* attribute exists with an element or not.

For example, you can check if a data-color attribute is set on the img element using the hasAttribute() method.

<img src="/images/javascript.png" id="logo" alt="JavaScript Logo" />
let image = document.getElementById('logo');
let imageSource = image.hasAttribute('data-color');
  console.log('data-color attribute is mentioned.');
  image.setAttribute('data-color', 'yellow')

Recommended Posts