Change or set HTML tag attribute using jQuery

. Sunday, June 15, 2008
  • Agregar a Technorati
  • Agregar a
  • Agregar a DiggIt!
  • Agregar a Yahoo!
  • Agregar a Google
  • Agregar a Meneame
  • Agregar a Furl
  • Agregar a Reddit
  • Agregar a Magnolia
  • Agregar a Blinklist
  • Agregar a Blogmarks

It is sometimes necessary to change the attributes of a particular HTML tag of your webpage using javascript, especially when you are coding rich web applications. Let it be the class of an element, or the href attribute of an anchor tag.

In this tutorial, I am going to show you how to do it utilising jQuery javascript library quickly.

HTML code (inside BODY tag)
First, we will place a sample image and a link in our webpage.

<a id="clickMe" href="#">Change the image below</a>
<br />
<img id="myimage" src="current_image_file.jpg" />

Now we want the src attribute to change from current_image_file.jpg to new_image_file.jpg (a click event will be required).

jQuery code (place this JavaScript inside HEAD tag)
<script type="text/javascript" src=".jquery.js"></script>
<script type="text/javascript">
function() {
"#clickMe").click(function() {
"#myimage").attr({src : "new_image.gif"});


Sandy said...

hi! nice tutorial again. i really like your posts - so well formatted. this piece of code will probably help me implement an ajax photo gallery in my site. thanks :)

Anonymous said...

How do I get my original image back?

Anonymous said...

where is .jquery.js ????