HTML DOM Attributes setNamedItem() Methode

Definition and usage

setNamedItem() The method adds the attribute node to the NamedNodeMap.

If the attribute node already exists, it will be replaced and the replaced attribute node will be returned, otherwise the return value will be null.

Alternative:

Use element.setAttribute() The method is easier.

See also:

attribute.value property

attribute.name property

attributes.getNamedItem() method

element.setAttribute() method

element.setAttributeNode() method

Example

Example 1

Set the H1 class attribute:

const nodeMap = document.getElementsByTagName("H1")[0].attributes;
const node = document.createAttribute("class");
node.value = "democlass";
nodeMap.setNamedItem(node);

Try it yourself

Example 2

It's easier to use element.setAttribute():

const element = document.getElementsByTagName("H1")[0];
element.setAttribute("class", "democlass");

Try it yourself

Syntax

namednodemap.setNamedItem(node)

Parameter

Parameter Description
node Required. The node to be added or replaced in the NamedNodeMap.

Return value

Type Description
Node The replaced node (if any). Otherwise, return null.

Browser support

attributes.setNamedItem Is a DOM Level 1 (1998) feature.

All browsers support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Supported 9-11 Supported Supported Supported Supported