ManticMoo.COM -> Jeff's Articles -> Programming Articles -> Setting the alt attribute with Javascript

Setting the alt attribute with Javascript

by Jeffrey P. Bigham

It can be quite handy to manipulate the attributes of HTML tags programatically using javascript. The following code snippet demonstrates a very straightforward example of this which simply sets the alt attribute of an image tag to the source of the image upon it finishing loading. I'm not sure why you would want to do this exactly (I have reasons relating to a Brable), but it is illustrative for a variety of purposes. The setAttribute function allows you to set the value of any attribute of your choosing.

Code Snippet


<script>
function set_alt_attribute(image) {
  image.setAttribute("alt", image.src);
}
</script>

<img src="my_image.jpg" onLoad="set_alt_attribute(this);">

Example

The following image has both an alt attribute that reads "puppy" and a more descriptive longdesc attribute that describes important features about the photo including that the puppy is very young and small enough to be held in someone's hand.
puppy
That's all there is to it!

ManticMoo.COM -> Jeff's Articles -> Programming Articles -> Setting the alt attribute with Javascript