Working with the Attribute Node

An attribute is contained inside an element node. It is not a child of that node.

In the below example id="header" is an attribute node.
<div id="header"></div>

The following are the methods to get, modify, or remove that information. 

■ hasAttribute()
■ getAttribute()
■ setAttribute()
■ removeAttribute()

For example of class="visible", we would be targeting “class” and return the value “visible”.

hasAttribute()


Before we target an attribute, to make sure an element contains the attribute we’re looking for, use hasAttribute() method. It returns true if the attribute exists.

<img src="images/placeholder.png" class="show" alt="placeholder image" id="plc">

// first we target the element and check if it has a class on it
if(document.getElementById("plc"). hasAttribute ("class")) {
// logic here
}

getAttribute()


The getAttribute() method takes one argument, which is the name of the attribute you want to target.

<img src="images/placeholder.png" class="show" alt="placeholder image" id="plc">

document.getElementById("plc").getAttribute("class");
// this would return the value of "show", which is the class on our image

setAttribute()


The setAttribute() method is used for setting a attribute(like class), or replacing an attribute with something new. This method has a built-in if statement, so we don’t need to check if the attribute exists.

This method takes two arguments—the first is the name of the attribute, and the second is the value you want to set it to.

<img src="images/placeholder.png" class="show" alt="placeholder image" id="plc">

// replace the current class with a value of "hidden"
document.getElementById("plc"). setAttribute ("class", "hidden");
// add a new attribute to the image
document.getElementById("plc"). setAttribute ("title", "we moved this element off screen");
In this example, we changed the class from “ visible ” to “ hidden ”

removeAttribute()


The removeAttribute() is used to remove an attribute node from an element. Just target the element node and use the method removeAttribute() to get it out of there. 

If you try to remove an attribute that doesn’t exist, Javascript will not throw exception. It’s still a best practice to use the hasAttribute() method.

// first we target the element and check if it has a class on it
if(document.getElementById("plc"). hasAttribute ("class")) {
// after we know a class exists, we can then remove it
document.getElementById("plc"). removeAttribute ("class"); }

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents