1. Technology

JavaScript By Example

Document Object Model: 12. Set Attributes


As with getting attributes, there are two ways to set attributes. One way is to use the setAttribute() method and the other is to just directly reference the property corresponding to the attribute. The same proerty names apply for setting attributes as for getting them with the only two that do not match exactly to the actual attribute names being the className proerty to reference the class attribute and the htmlFor property to reference the for attribute.

One thing to note is that event handlers are not attributes and so cannot be set via the setAttribute() method. Also, while you can set them via the correspondingly named property, you should not do so for any element that already exists in the web page and should instead use event listeners (as already covered in the events examples). That way you avoid the possibility of the event processing in this script conflicting with event processing performed by any other script attached to the same page. You can safely attach event handlers this way to elements that your script adds to the web page as those elements will only exist once your script creates them and so other scripts will not expect them to be there.

Setting a new attribute directly affects the content of the page. In this example we update the src attribute of an image within the page which will have the effect of replacing the image that is displayed in the web page.

In this example we update an image in the web page to reflect whatever season it currently is in the southern hemisphere (setting north to true would switch it to display the season in the northern hemisphere).


<title>Example D12</title>
<img id="season" src="summer.gif" alt="season">
<script type="text/javascript" src="exampleD12.js"></script>


var north, backImg, today, month;
north = false;
backImg = ['summer.gif','autumn.gif','winter.gif','spring.gif'];
today = new Date();
month = today.getMonth();
if (today.getDate() > 20) month++;
document.getElementById('season').src =

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Document Object Model
  7. JavaScript By Example - DOM: Set Attributes

©2014 About.com. All rights reserved.