DOM getAttribute()
As we create HTML elements in JavaScript, we can create and delete their attributes. For this, we use the setAttribute () method to create the attribute, the removeAttribute () method to delete the attribute, the getAttribute () method to find the attribute value, and the hasAttribute () method to check the attribute.
- setAttribute ()
- removeAttribute ()
- getAttribute ()
- hasAttribute ()
getAttribute()
The JavaScript getAttribute () property returns the value of a named attribute. Note that the HTMLElement object defines the JavaScript properties that match each of the standard HTML attributes; therefore, if you only query the value of non-standard attributes, you must use this method with HTML documents.
Syntax:
element.getAttribute(name)
name: Enter the name of the attribute to which you want to retrieve the value.
getAttribute Examples
Example 1
<body>
<input type="text" value="truecodes.org"/>
<button onclick="myAttribute();">TRANSLATE</button>
<div id="result"></div>
<script>
function myAttribute() {
document.getElementsByTagName("INPUT")[0].setAttribute("type", "button");
let type = document.getElementsByTagName("INPUT")[0].getAttribute("type");
document.getElementById("result").innerHTML = type;
}
</script>
</body>
Example 2
<body>
<button id="but" onclick="myButton()">BUTTON</button><br />
<div id="result"></div>
<script>
function myButton() {
let info = document.getElementById("but").getAttribute("onclick");
document.getElementById("result").innerHTML = info;
}
</script>
</body>
Example 3
<body>
<button id="but" onclick="myButton()">BUTTON</button><br />
<p onmousedown="onmousedownFunction()"></p>
<div id="result"></div>
<script>
function myButton() {
let info = document.getElementsByTagName("P")[0].getAttribute("onmousedown");
document.getElementById("result").innerHTML = info;
}
</script>
</body>
4 Comments »