tags:

views:

16

answers:

4

Hello!

I have this HTML markup

<a href="#" title="">
   <img src="#" title="image1" />
</a>

<a href="#" title="">
   <img src="#" title="image2" />
</a>

<a href="#" title="">
   <img src="#" title="image3" />
</a>

and I need to take the title of each image and put it on their "a". I tried to do it with this function

   $(function() {

    var title = $('a').find('img');

    var updateTitle = title.attr('title');

    $('a').attr({
      title: updateTitle,
      alt: 'lol'
     });
 });

But the only result is the same title for all "a" (the first title he finds)

Any help????

Thank you very much

A: 

Try this:

$('a').each(function() {
    var title = $(this).find('img');

    var updateTitle = title.attr('title');

    $(this).attr({
      title: updateTitle,
      alt: 'lol'
     });
};

The attr() method only acts on the first element of the wrapped set. The same applies for other jQuery methods as well. Using the each utility method is very convenient for cases like this.

kgiannakakis
+1  A: 
$(function() {
    $('a > img').each(function() {
        this.parentNode.title = this.title;
        this.parentNode.alt = 'lol';
    });
});

or

$(function() {
    $('a:has(img)').attr('title', function() {
        return $(this).children('img').attr('title');
    }).attr('alt', 'lol');
});
patrick dw
This is essentially the same as mine, backwards. I think mine will have better performance, because the selector is simpler (`a` vs `a > img`). What do you think?
lonesomeday
@lonesomeday - Trouble is that `firstChild` will fail in W3C compliant browsers, because the first child will be an empty text node, whereas in IE, empty spaces are not made into text nodes. I'd also suggest that the check for an `<img>` would be necessary to avoid tampering with `<a>` elements that don't have a child image.
patrick dw
Fair points. +1
lonesomeday
A: 

Here is modified function. You have to loop through each anchor tag and update its attributes accordingly

$('a').each(function(){

    var title = $(this).find('img');

    var updateTitle = title.attr('title');

    $(this).attr({
      title: updateTitle,
      alt: 'lol'
     });
});
Chinmayee
A: 

Use the callback signature of attr:

$(function(){
    $('a').attr('title', function() {
        return $(this).find('img').attr('title');
    });
});

Edited to work reliably Note that this is less efficient than patrick dw's version.

lonesomeday