Search code examples
javascriptimageprototypejs

Getting the alt attribute of an image in prototype


I'm editing some old sideshow code someone else written a while ago and I was wondering how you get the alt attribute of an image with prototype.

Ive got the image tag selected with the code below:

$$('#' + this.slides[this.currentSlide].id + ' a img')

But for the life of me I don't know how to get the alt text.

I've tried...

$$('#' + this.slides[this.currentSlide].id + ' a img').alt;
$$('#' + this.slides[this.currentSlide].id + ' a img').alt();
$$('#' + this.slides[this.currentSlide].id + ' a img').readAttribute('alt');

Could anyone help.


Solution

  • The $$ utility method returns an array. You need to get the element out of the array and then read its attribute.

    var elements = $$('#' + this.slides[this.currentSlide].id + ' a img');
    if (elements.length > 0) {
       var altText = elements[0].readAttribute('alt');
       alert(altText);
    }