Working with Attributes in DOM


This article will take you on the tour of Attribute manipulation methods in JavaScript, though very easy these methods are really handy and worth learning.

Demonstration Tools: Firefox - Firebug tool

In this tutorial we are going to brief another part of DOM which can be manipulated with JavaScript, that is Attributes. We are presenting working tutorials about the four methods provided by JavaScript to access and make changes to an attribute. For the Demonstration purpose we are using a blank HTML document with only an Image tag with some attributes.


<html>
	<body>
		<img src="image.jpeg" class="image" id="demoImage" alt="Demo Image"/>
	</body>
</html>

There are four methods JavaScript comes with to give access to the Attribute Node of an element DOM.

		getAttribute();
		setAttribute(,);
		hasAttribute();
		removeAttribute();
	

 

getAttribute

getAttribute is as the name suggest a method that returns the value of an attribute. As you can see in the example below, when we invoke the method on the element Node this return the value of the attribute we pass as an argument.


document.getElementById("demoImage").getAttribute("alt");

Demo Image

setAttribute

This method allows us to make changes to an existing attribute or add a new attribute to the element. This takes two arguments, which are a pair of key and value for the attribute and its value.


document.getElementById("demoImage").setAttribute("title","Image Title");

<img src="image.jpeg" class="image" id="demoImage" alt="Demo Image" title="Image Title"/>

hasAttribute

This method takes in the name of attribute and return true if the attribute exists and false if it does not.


console.log(document.getElementById("demoImage").hasAttribute("alt"));
console.log(document.getElementById("demoImage").hasAttribute("style"));

true
false

removeAttribute

Takes the name of an attribute and remove that attribute if that exists in the element DOM.


document.getElementById("demoImage").removeAttribute("alt");

	<img class="image" id="demoImage" src="image.jpeg" title="Image" />

Well, this is it. Now you are armed with the knowledge of attribute manipulation method of JavaScript, any query or feedback please comment below.