I have come across 2 ways of getting a value of attribute: first is:
document.getElementById("id").getAttribute("class");
document.getElementById("id").setAttribute("class", "newClass");
the other:
document.getElementById("id").className;
Both can be used to set and get class value or any other value. Are there specific situations where one is preferable? Is one faster than the other? How do they differ? Why even have 2 ways of doing it?
They do different things. The .getAttribute('name')
gets the attribute, while .name
get the property.
The attribute is the initial value set by the attribute in the HTML code when the element is created. The property is the current value, which may have changed since the element was created.
For some properties the attribute change along with the property, but for some the property and attribute are separate values:
window.onload = function(){
var el = document.getElementById("id");
console.log("Attribute: " + el.getAttribute("value"));
console.log("Property: " + el.value);
console.log('Changing property');
el.value = 'b';
console.log("Attribute: " + el.getAttribute("value"));
console.log("Property: " + el.value);
};
<input type="text" id="id" value="a"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With