2

I need some help, and before we get going, I know it is probably not best practice, but I am doing some maintenance to an existing site and need to accomplish the following for a fix.

<a rel="lightbox" href="site.com" title="a generated title">
    <img src="site.com/img" class="post-image" alt="a long description"/>
</a>

Okay, so I am trying to figure out how to use jQuery or any other method to take the alt attribute from my image, and dynamically overwrite the title attribute of my a tag.

Any help would be awesome, I am kinda lost at this juncture.

Smandoli
  • 6,919
  • 3
  • 49
  • 83
Brock
  • 173
  • 3
  • 13

5 Answers5

7
$(function(){
   $("a").each(function(){
        $(this).attr("title", $(this).find("img").attr("alt"));
   });
});
Curtis
  • 101,612
  • 66
  • 270
  • 352
  • Sir, you are a scholar and a gentlemen. That seemed so obvious, not sure why I didn't see it. Nonetheless. Thank you! – Brock Jun 28 '12 at 15:34
2

you didn't mention exactly which <a>s you wanted to change, so this would change all <a>s with an <img> inside...

$("a>img").each(function() {
  $(this).parent().attr("title", $(this).attr("alt"))
})
Rodolfo
  • 4,155
  • 23
  • 38
0

With jQuery:

var a = $('a[rel=lightbox])');
var img = a.find('img');
a.attr('title', img.attr('alt'));
Attila Szeremi
  • 5,235
  • 5
  • 40
  • 64
0
$('a').each(function(){
    $(this).attr('title',$(this).find('img').attr('alt'));
});

Since jsFiddle.net seems to be flaky over the last day or so, you can see a demo at jsbin.

And if jsFiddle loads, a jsFiddle example.

j08691
  • 204,283
  • 31
  • 260
  • 272
0

You can do it like this:

$(function() {
    var img = $(".post-image");
    if(img.length == 1) // meaning, at least one element was found
    {
        img.attr("title", img.attr("alt")); // pass the text in alt to title
        img.removeAttr("alt");              // remove alt
    }
});
MilkyWayJoe
  • 9,082
  • 2
  • 38
  • 53