To check if the element has a specific attribute in JavaScript, you can use the hasAttribute()
method in the element.
Let's say you have an h1
element with custom attribute data-color="red"
like this,
<h1 data-color="red">Heading</h1>
Now let's check is the data-color
custom attribute is present in the h1
tag element using the hasAttribute()
method in it.
// get the reference to the h1 tag element
const h1 = document.querySelector("h1");
// chcek if h1 tag has attribute : data-color
const isPresent = h1.hasAttribute("data-color");
console.log(isPresent); // true;
-
The
hasAttribute()
method accepts a valid name of the attribute as a string. -
The method return boolean
true
is present andfalse
is not present.
See live example in JSBin.