What is the DOM setAttributeNode() method?

Overview

In this shot, we will learn how to set a new attribute node in an HTML element.

The setAttributeNode() method sets the attribute nodeEverything in an HTML document is a node. that is passed as a parameter to the element it is applied on.

Code

Let’s write a code to set an attribute node to an element.

Code explanation

  • In line 5, we set the CSS class 'new' with a color property to ‘yellow’.
  • In line 12, we add the new CSS in the DIV element with id div.
  • In line 14, we include a paragraph tag with text.
  • In line 16, we write a button tag with the change() function, which will be called when the user clicks on the button.
  • In line 19, we write the JavaScript code in the script tag. The change() function will be called when a user clicks the button from the HTML page.
  • In line 20, we create a new attribute Node class.
  • In line 21, we assign a value to the new attribute ‘class’.
  • In line 22, we get the div element with id div.
  • In line 23, we use the setAttributeNode() method to add the new attribute Node in the DIV element.

Output

When we click the button, the color of the DIV element changes, which means the new CSS class has been successfully added to the selected element.

Free Resources