This post will discuss how to check whether an element has the specified attribute or not in JavaScript and jQuery.

1. Using jQuery

The idea is to use the .attr() method, which returns the attribute’s value for an element if it is present and returns undefined if the attribute doesn’t exist.

JS


HTML



Edit in JSFiddle

 
Alternatively, you can use the Has Attribute Selector [name] to select elements having the specified attribute.

JS


HTML



Edit in JSFiddle

2. Using JavaScript

In pure JavaScript, you can use the hasAttribute() method to determine whether the specified element has the specified attribute.

JS


HTML



Edit in JSFiddle

That’s all about checking the existence of an attribute in JavaScript and jQuery.