As we create HTML elements in JavaScript, we can create and delete their attributes. For this, we use the setAttribute () method to create the attribute, the removeAttribute () method to delete the attribute, the getAttribute () method to find the attribute value, and the hasAttribute () method to check the attribute.
- setAttribute ()
- removeAttribute ()
- getAttribute ()
- hasAttribute ()
hasAttribute
The hasAttribute () method returns true if the specified attribute exists, otherwise false.
Syntax:
element.hasAttribute(name)
name: The attribute name that you want to check if it exists.
hasAttribute Examples
Example 1
<body>
<div class="box">
<input class="txt" type="text" value="box list" />
<span onclick="removeFunction()"><i class="fas fa-times"></i></span>
</div>
<script>
function removeFunction() {
let bloen = document.querySelector(".box").hasAttribute("class");
if (bloen === true) {
document.querySelector(".box").removeAttribute("class");
}
else {
document.querySelector(".box").setAttribute("class");
}
}
</script>
</body>
Example 2
<body>
<p>Click the button to find out if the button element has an onclick attribute.</p>
<button id="myBtn" onclick="myFunction()">Try it</button>
<p>Internet Explorer 8 and earlier does not support the hasAttribute() method.</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myBtn").hasAttribute("onclick");
document.getElementById("demo").innerHTML = x;
}
</script>
</body>