HTML DOM Attributes setNamedItem() Method

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:

Usage 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 class attribute of H1:

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 returns null.

Browser Support

attributes.setNamedItem It is a DOM Level 1 (1998) feature.

All browsers support it:

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