The getAttribute()
method returns the
value of the attribute for the specified name.
getAttribute |
Yes | Yes | Yes | Yes | Yes |
element.getAttribute(attributename)
Parameter | Type | Description |
---|---|---|
attributename | String | Required. The name of the attribute |
Return the specified attribute's value in String type value.
The following code shows how to get the target attribute value of a link.
<!DOCTYPE html>
<html>
<body>
<a href="http://example" target="_blank">Attr object</a>.
<p id="demo">test</p>
<button onclick="myFunction()">test</button>
<script>
function myFunction()<!-- w w w.j a v a2 s . co m-->
{
var a=document.getElementsByTagName("a")[0];
document.getElementById("demo").innerHTML=a.getAttribute("target");
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code sets and gets attributes for an element.
<!DOCTYPE HTML>
<html>
<body>
<p id="textblock" class="Survey numbers">
This is a test. <!--from w w w . j av a2 s . c o m-->
</p>
<pre id="results"></pre>
<script>
var elem = document.getElementById("textblock");
document.writeln("lang attribute: " + elem.hasAttribute("lang"));
elem.setAttribute("lang", "en-US");
document.writeln("Attr value is : " + elem.getAttribute("lang"));
elem.setAttribute("lang", "en-UK");
document.writeln("Value is now: " + elem.getAttribute("lang"));
</script>
</body>
</html>