Element hasAttribute() Method - Javascript DOM

Javascript examples for DOM:Element hasAttribute

Description

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

Parameters

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>
<html>
<body>

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

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

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

    if (x.hasAttribute("target")) {
        x.setAttribute("target", "_self");
    }
}
</script>

</body>
</html>

Related Tutorials