Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

className vs. get/setAttribute method

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?

like image 523
potato Avatar asked Dec 19 '22 22:12

potato


1 Answers

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>
like image 166
Guffa Avatar answered Dec 21 '22 11:12

Guffa