JavaScript DOM NamedNodeMap method: setNamedItem()
[this page | pdf | back links]
The setNamedItem() method (when applied to
NamedNodeMap objects in the JavaScript
DOM) adds /
sets a specified node (specified by name). If the node already existed then the
old node will be replaced. If it didn’t previously exist then it will be
addNote: if you are setting an element attribute then you can use the element.setAttribute()
instead.
It
has the following syntax with the following parameters. It returns a node
object representing the replaced object (if any), or null if no replacement occurred.
namednodemap.setNamedItem(node)
Parameter
|
Required / Optional
|
Description
|
node
|
Required
|
Node object to be added
or to replace the relevant old node
|
EXAMPLE:
HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>.myclass {font-style: italic;}</style>
</head>
<body>
<a href="http://www.nematrian.com" id="element">link to www.nematrian.com</a>
<br>(initially has 2 attributes, i.e. href = http://www.nematrian.com and id = element)
<br><br><em>NamedNodeMap items for this hyperlink:</em><br>
initial number of nodes: <b><span id="nnm1"></span></b><br>
name and value of first attribute: <b><span id="nnm2"></span></b><br>
name and value of href attribute: <b><span id="nnm3"></span></b><br>
number of nodes after adding class and hreflang nodes (class changes hyperlink styling): <b><span id="nnm4"></span></b><br>
number of nodes after removing hreflang node: <b><span id="nnm5"></span></b><br>
<script>
var x = document.getElementById("element").attributes;
document.getElementById("nnm1").innerHTML = x.length;
var y1 = x.item(0);
document.getElementById("nnm2").innerHTML = y1.name + ", " + y1.value;
var y2 = x.getNamedItem("href");
document.getElementById("nnm3").innerHTML = y2.name + ", " + y2.value;
var c1 = document.createAttribute("class");
c1.value = "myclass";
x.setNamedItem(c1);
var c2 = document.createAttribute("hreflang");
c2.value = "en-uk";
x.setNamedItem(c2);
document.getElementById("nnm4").innerHTML = x.length;
x.removeNamedItem("hreflang");
document.getElementById("nnm5").innerHTML = x.length;
</script>
</body>
</html>
|
NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)