Element hasAttribute() Method - Javascript DOM

Javascript examples for DOM:Element hasAttribute


The hasAttribute() method returns true if the specified attribute exists, otherwise it returns false.


Parameter Type Description
attributename String Required. The name of the attribute you want to check

Return Value:

A Boolean, returns true if the element has attributes, otherwise false

The following code shows how to Find out if a <button> element has an attribute:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>

<a id="myAnchor" href="http://www.java2s.com" target="_blank">go to java2s.com</a>.

<button id="myBtn" onclick="myFunction()">Test</button>

function myFunction() {/*ww w.j  a v a2 s . co m*/
    var x = document.getElementById("myAnchor");

    if (x.hasAttribute("target")) {
        x.setAttribute("target", "_self");


Related Tutorials