Using JavaScript, the easiest way to check if an attribute exists in an HTML element is to use the hasAttribute() method.

element.hasAttribute("href")

Here we can see how we can use this information in an if-else statement.

if (element.hasAttribute("href")){
  console.log("HTML element has attribute href!");
} else {
  console.log("HTML element does not have attribute href!");
}

And then we can see it all come together in an HTML example:

Check out our website!

The Programming Expert


var element = document.getElementById("home-page");
if (element.hasAttribute("href")){
  console.log("HTML element has attribute href!");
} else {
  console.log("HTML element does not have attribute href!");
}

#Output:
HTML element has attribute href!

So to recap, we can check if an object has an attribute with the hasAttribute() method. The hasAttribute() method will return a boolean value of true or false depending on whether the element being checked has the attribute or not.

Below are some examples of using the hasAttribute() method to check if different attributes exist.

Check out our website!

The Programming Expert


var element = document.getElementById("home-page");
console.log(element.hasAttribute("href"));
console.log(element.hasAttribute("class"));
console.log(element.hasAttribute("target"));
console.log(element.hasAttribute("id"));
console.log(element.hasAttribute("src"));

#Output:
true
true
true
true
false

If you want to learn how to remove an attribute, make sure to check out this post.

Hopefully this article has been helpful for you to learn how to use JavaScript to check if an attribute exists.

Categorized in:

JavaScript,

Last Update: May 3, 2024