HTML DOM hasAttributes() method


The HTML DOM hasAttributes() method checks if an element has any attributes or not. It returns true if the element does contain any attribute and returns false if it doesn’t. If this method is called on any other node than the element node, the returned value will always be false.

Syntax

Following is the syntax for hasAttribbutes() method −

node.hasAttributes()

Example

Let us look at an example for the hasAttributes() method −

<!DOCTYPE html>
<html>
<body>
<h1>hasAttributes() example</h1>
<p>This paragraph has no attributes</p>
<button onclick="containsAttr()">CHECK</button>
<p id="Sample">The paragraph above hasAttribute value : </p>
<script>
   function containsAttr() {
      var p = document.getElementsByTagName("P")[0];
      document.getElementById("Sample").innerHTML+=p.hasAttributes();
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CHECK button −

In the above example −

We have created a paragraph that has no attributes associated with it −

<p>This paragraph has no attributes</p>

We have then created the CHECK button that executes the checkAttr() method on being clicked by the user −

<button onclick="containsAttr()">CHECK</button>

The containsAttr() method gets the first <p> element using the getElementsByTagName() method and using the index to get the first element and assigns it to variable p. It then calls the hasAttributes() method upon the variable p and returns false since our first <p> element has no attributes. This value is appended to the paragraph with id “Sample” using its innerHTML property:

function containsAttr() {
   var p = document.getElementsByTagName("P")[0];
   document.getElementById("Sample").innerHTML+=p.hasAttributes();
}
raja
Published on 09-Aug-2019 08:37:34
Advertisements