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:

htmlElement.hasAttribute('attributeName');

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

HTML Code

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

JavaScript Code

let image = document.getElementById('logo');
let imageSource = image.hasAttribute('src');
if(imageSource){
  console.log('Image source is mentioned.');
}else{
  image.setAttribute('src', 'https://www.tutorialsandyou.com/images/javascript.png');
}

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');
if(imageSource){
  console.log('data-color attribute is mentioned.');
}else{
  image.setAttribute('data-color', 'yellow')
}

Recommended Posts