JavaScript - hasAttributes() method

revision:


Category : element

The hasAttributes() method of the Element interface returns a boolean value indicating whether the current element has any attributes or not.

The hasAttributes() method returns true if a node has attributes, otherwise false. The hasAttributes() method always returns false if the node is not an element node.

Syntax :

        element.hasAttributes()
        node.hasAttributes();
    

Parameters: none

Examples:

            let foo = document.getElementById("foo");
            if (foo.hasAttributes()) {
              // Do something with 'foo.attributes'
            }
        

Practical examples

example: does the <body> element have attributes?

The body element has attributes:

code:
                    <div>
                        <p>The body element has attributes:</p>
                        <p id="attr-1"></p>
                    </div>
                    <script>
                        let answer = document.body.hasAttributes();
                        document.getElementById("attr-1").innerHTML = answer;
                        
                    </script>
                

example: does the <div> element have attributes?
do I have attributes?
code:
                    <div>
                        <div id="div1" style="background: green; border: 0.1vw solid red; color: orange;">do I have attributes? <span id="attr-2"></span> </div>
                    </div>
                    <script>
                        let answer1= document.getElementById("div1").hasAttributes();
                        document.getElementById("attr-2").innerHTML = answer1;    
                    </script>
                

example: does the <button> element have attributes?
code:
                    <div>
                        <div>
                            <button id="btn1" style="background: lightgreen; border: 0.1vw solid blue; color: indigo;">do I have attributes? <span id="attr-3"></span> </button>
                        </div>
                    </div>
                    <script>
                        let answer2= document.getElementById("btn1").hasAttributes();
                        document.getElementById("attr-3").innerHTML = answer2;  
                    </script>