JavaScript - getAttribute() method

revision:


Category : element

The getAttribute() method of the Element interface returns the value of a specified attribute on the element.If the given attribute does not exist, the value returned will either be null or "" (the empty string).

Syntax :

        element.getAttribute(attributeName)
    

Parameters:

attributeName : required; is the name of the attribute whose value you want to get.

Examples:

            let nonce = script.getAttribute("nonce");
            // returns empty string
            
        

Practical examples

example: using getAttribute() method.
Hi Champ!

code:
                    <div>
                        <!-- example div in an HTML DOC -->
                        <div id="div1">Hi Champ!</div>
                        <p id="get-1"></p>
                        <p id="get-2"></p>
                    </div>
                    <script>
                        // in a console
                        const div1 = document.getElementById("div1");
                        //=> <div id="div1">Hi Champ!</div>
                        const exampleAttr = div1.getAttribute("id");
                        //=> "div1"
                        document.getElementById("get-1").innerHTML = "element is :" + exampleAttr;
                        const align = div1.getAttribute("align");
                        //=> null
                        document.getElementById("get-2").innerHTML = "attribute is :" + align;
                    </script>
                

example: get the value of a "class" attribute of an element.

The Element Object

code:
                    <div>
                        <h4 id="myH4" class="democlass">The Element Object</h4>
                        <p id="get-3"></p>
                        <p id="get-3"></p>
                    </div>
                    <script>
                        const element = document.getElementById("myH4"); 
                        let text = element.getAttribute("class"); 
                        document.getElementById("get-3").innerHTML = "attribute : " + text;
                    </script>
                

example: get the value of the "target" attribute of an <a> element.

Learn more about the my website.

The value of the target attribute of the link above is:

code:
                    <div>
                        <p>Learn more about the <a id="myAnchor" href="https://www.lwitters.com" target="_blank">my website</a>.
                        <p>The value of the target attribute of the link above is:</p>
                        <p id="get-4"></p>
                    </div>
                    <script>
                        const myAnchor = document.getElementById("myAnchor") 
                        let text1 = myAnchor.getAttribute("target");
                        document.getElementById("get-4").innerHTML = "target attribute value : " + text1;
                    </script>