JavaScript - setAttributeNode() method

revision:


Category : element

The setAttributeNode() method adds a new Attr node to the specified element.

The setAttributeNode() method adds an attribute node to an element. It replaces existing attribute nodes and returns an Attribute object.

Syntax :

        setAttributeNode(node)
    

Parameters:

node : required; the Attr node to set on the element.

Examples:

            <div>
                <div id="one" align="left">one</div>
                <div id="two">two</div>            
            </div>
            <script>
                let d1 = document.getElementById("one");
                let d2 = document.getElementById("two");
                let a = d1.getAttributeNode("align");
    
                d2.setAttributeNode(a.cloneNode(true));
    
                // Returns: 'left'
                alert(d2.attributes[1].value);
                
            </script>
        

Practical examples

example: set the class attribute node of the first <h4> element.

The Element Object

Click "Change" to set the class attribute node of the first header.

code:
                    <div>
                        <h4>The Element Object</h4>
                        <p>Click "Change" to set the class attribute node of the first header.</p>
                        <button onclick="changeNode()">Change</button>
                    </div>
                    <style>
                        .democlass {color: red;}
                    </style>
                    <script>
                        function changeNode() {
                            const attr = document.createAttribute("class");
                            attr.value = "democlass";
                        const element = document.getElementsByTagName("H4")[0];
                        element.setAttributeNode(attr); 
                        }
                    
                    </script>
                

example: set the href attribute of an <a> element.
Go to lwitters.com

Click "add" to add an href attribute to the element above.

code:
                    <div>
                        <a id="myAnchor">Go to lwitters.com</a>
                        <p>Click "add" to add an href attribute to the element above.</p>
                        <button onclick="addAttribute()">change</button>
                    </div>
                    <script>
                        function addAttribute() {
                            // Create a href attribute:
                            const attr = document.createAttribute("href")
                            // Set the value of the href attribute:
                            attr.value = "https://www.lwitters.com";
                            // Add the href attribute to an element:
                            document.getElementById("myAnchor").setAttributeNode(attr);
                        }
                    </script>