Getting and Setting Attributes

All HTML elements have a large number of possible attributes such as class, idsrc, and href. The DOM API contains getter and setter methods that can be used to view, add, remove, or modify the value of any of these attributes.


Getting an Element’s Attributes

The getAttribute() method returns the value of the attribute provided as an argument: 


swim.getAttribute("class");
<< "swim"

var meta = document.getElementsByTagName("meta")[0];
<< undefined

meta.getAttribute("charset");
<< "utf-8"
  

If an element does not have the given attribute, it returns null: 


swim.getAttribute("stroke");
<< null
  


Setting an Element’s Attributes

The setAttribute can change the value of an element’s attributes. It takes two arguments: the attribute that you wish to change and the new value of that attribute.
For example, if we wanted to change the class of the swim element to swimming, we could do so using this code: 


swim.setAttribute("class", "swimming");
<< undefined

swim.getAttribute("class");
<< "swimming"
  

If an element does not have an attribute, the setAttribute method can be used to add it to the element. For example, we can add an id of "run" to the run paragraph:  



run.setAttribute("id","run");
<< undefined

run.getAttribute("id");
<< "run"
  


Legacy DOM Attributes

The legacy DOM allows access to attributes using dot notation, like so:


bike.id;
<< "bike"
  

This notation is still supported, although some attribute names such as class and for are reserved keywords in JavaScript so we need to use className and htmlFor instead: 


swim.className;
<< "swim"
  

0 Response to "Getting and Setting Attributes"

Post a Comment