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 a single parameter node which is mandatory. This parameter is the node value that need to add or replace in the namedNodeMap collection.
Return Value: It returns a Node object that, represents the replaced node (if any), otherwise null
Example 1: In this example, we will use the setNamedItem() method.
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
let one =
document.getElementsByClassName("geeks1")[0];
// New class (geek) is created
let 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:
Example 2: In this example, we will use the setNamedItem() method.
HTML
<!DOCTYPE html>
< html >
< head >
< title >
DOM setNamedItem() Method
</ title >
< 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() {
let one =
document.getElementsByTagName("H1")[0];
let geek =
document.createAttribute("class");
geek.value = "gfg";
one.attributes.setNamedItem(geek);
let two =
document.getElementsByTagName("H3")[0];
let geek1 =
document.createAttribute("class");
geek1.value = "gfg1";
two.attributes.setNamedItem(geek1);
}
</ script >
</ body >
</ html >
|
Output:
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