Accessing Attribute Nodes

Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.

Contact Us or call 1-877-932-8228
Accessing Attribute Nodes

Accessing Attribute Nodes


The getAttribute() method of an element node returns the attribute value as a string or null if the attribute doesn't exist. The syntax is shown below:


Most HTML attributes are also directly available as properties of the element node; for example, for an img tag element, the width, height, and source are available as the width, height, and src properties.


The attributes[] property references the collection of a node's attributes; in practice, though, it's better to access attributes with the getAttribute() method.


The hasAttribute(attName) method returns a Boolean (true/false) value indicating whether or not the element to which the method is applied includes the given attribute. For example, the code

var newsletterlink = document.getElementById("newsletterlink");
if (newsletterlink.hasAttribute("target")) {
	alert("newsletter link opens in new window");

would pop up a JavaScript alert if the link with id newsletterlink had a target attribute, such as:

<a href="nl.pdf" id="newsletterlink" target="_blank">View Newsletter</a>

Note that method hasAttribute() does not check the value of the attribute, only if the attribute exists for the given element.


Method setAttribute(attName, attValue) allows us to add the given attribute to an element (if the attribute does not exist) or to change it (if the attribute does exist), and assign the given value. For instance, if we had this HTML:

<a href="nl.pdf" id="newsletterlink" target="_blank">View Newsletter</a>

then the following code:

var newsletterlink = document.getElementById("newsletterlink");
newsletterlink.setAttribute("target", "_self");

would change the value of the target attribute to _self.


Method removeAttribute(attName) removes the attribute from an element; attempting to remove an attribute that does not exist does not produce an error. The following code

var newsletterlink = document.getElementById("newsletterlink");

would remove the target attribute from the link, if the link had that attribute.


This tutorial is based on Webucator's Introduction to JavaScript Training Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.