HTML | DOM setNamedItem() Method
The setNamedItem() method is used to add a particular node to an attribute node using its name. These attribute nodes are collectively called as namedNodeMap. It can be accessed through a name. If a node is already present in the document, it will replace it and return the updated value. The setNamedItem() method requires a node as a parameter.
Syntax:
namedNodeMap.setNamedItem( node )
Parameter Value: This method contains single parameter node which is mandatory. This parameter is the node value which need to add or replace in namedNodeMap collection.
Return Value: It returns a Node object that , representing the replaced node (if any), otherwise null
Example 1:
HTML
<!DOCTYPE html> < html > < head > < title > DOM setNamedItem() Method </ title > < style > .gfg { color:green; font-size: 40px; } </ style > </ head > < body > < h1 class = "geeks1" >GeeksforGeeks</ h1 > < h2 class = "geeks2" >DOM setNamedItem() Method</ h2 > < button onclick = "setNameItem()" > Set Node </ button > < script > function setNameItem() { // It is used to fetch the text // present in class geeks1 var one = document.getElementsByClassName("geeks1")[0]; // New class (geek) is created var geek = document.createAttribute("class"); // Passing value of gfg class into geek class geek.value = "gfg"; // Updating the CSS property of geeks1 // class to gfg class one.attributes.setNamedItem(geek); } </ script > </ body > </ html > |
Output:
Before Click on the button:
After Click on the button:
Example 2:
HTML
<!DOCTYPE html> < html > < head > < title > DOM setNamedItem() Method </ title > <!-- Set CSS property to the element --> < style > .gfg { color:green; font-size: 40px; } .gfg1 { color:green; font-size: 40px; } </ style > </ head > < body style = "text-align:center" > < h1 >GeeksforGeeks</ h1 > < h2 >DOM setNamedItem() Method</ h2 > < h3 >Welcome to GeeksforGeeks</ h3 > < button onclick = "setNameItem()" > Set Node </ button > < script > function setNameItem() { var one = document.getElementsByTagName("H1")[0]; var geek = document.createAttribute("class"); geek.value = "gfg"; one.attributes.setNamedItem(geek); var two = document.getElementsByTagName("H3")[0]; var geek1 = document.createAttribute("class"); geek1.value = "gfg1"; two.attributes.setNamedItem(geek1); } </ script > </ body > </ html > |
Output:
Before Click on the button:
After Click on the button:
Supported Browsers: The browser supported by DOM setNamedItem() Method are listed below:
- Google Chrome 1
- Edge 12
- Internet Explorer 6
- Firefox 1
- Opera 12.1
- Safari 1