JavaScript - hasAttribute() method

revision:


Category : element

The Element.hasAttribute() method returns a Boolean value indicating whether the specified element has the specified attribute or not.

Syntax :

        element.hasAttribute(name)
    

Parameters:

name : required; is a string representing the name of the attribute.

Examples:

            const foo = document.getElementById("foo");
            if (foo.hasAttribute("bar")) {
              // do something
            }
        

Practical examples

example: does "myButton" has an onclick attribute?

Does the button have an onclick attribute:

code:
                    <div>
                        <button id="myBtn" onclick="functionA()">BUTTON</button>
                        <p>Does the button have an onclick attribute:</p>
                        <p id="has-1"></p>
                    </div>
                    <script>
                        const myButton = document.getElementById("myBtn");
                        let answer = myButton.hasAttribute("onclick");
                        document.getElementById("has-1").innerHTML = answer;
                        
                    </script>
                

example: if an <a> element has a "target" attribute, change the value to "_self".
my website.

Click "Change" to change the link target to "_self_".

Try clicking the link before and after "Change".

code:
                    <div>
                        <a id="myA" href="https://www.lwitters.com" target="_blank">my website</a>.
                        <p>Click "Change" to change the link target to "_self_".</p>
                        <button onclick="functionB()">Change</button>
                        <p>Try clicking the link before and after "Change".</p>
                    </div>
                    <script>
                        function functionB() {
                            const element = document.getElementById("myA");
                            if (element.hasAttribute("target")) {
                                element.setAttribute("target", "_self");
                            }
                        }
                    </script>
                

example:
code: