HTML DOM attributes property

The attributes property returns a collection of the specified node's attributes, as a NamedNodeMap object. The basic syntax of attributes property is as follows :
 node.atttibutes
Now lets see an example :
<html>
<body>
  <p id="demo" class="paragraph" style="color: blue;">Hello world</p>
  <script>
    console.log(document.getElementById('demo').attributes);
  </script>
</body>
</html>
At the above code we are using console.log() method, which writes the messages to the console. The console is very useful for testing and debugging purposes. Now to open the console in your browser press F12 button, or goto Options on your browser window, click on Developer tools and then click on console tab.


Now when we run the above code, then it will print the attributes of the paragraph as an object.


Where it shows all three attributes id, class and style. and each attribute or node can be accessed by index numbers, and the index starts at 0. and the length is 3. Now to access each node, we can use :
  console.log(document.getElementById('demo').attributes[0]);
  console.log(document.getElementById('demo').attributes[1]);
  console.log(document.getElementById('demo').attributes[2]);


There are also various properties and methods are available by which we can modify and customize  the HTML elements attributes. Some of them are :
  • node.hasAttribute(name) – checks for existence.
  • node.getAttribute(name) – gets the value.
  • node.setAttribute(name, value) – sets the value.
  • node.removeAttribute(name) – removes the attribute.

Next Topic :

No comments:

Post a Comment