Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript inserting rel and title attr into anchor tags

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #33360
    DogsGhost
    Member

    I have mark up such as

    Gallery 2


    I want to get the title attr from an image and make it the title attr for that image’s link. I don’t have access the actual html to alter it by hand, so I was thinking I could use js to add a title tag my links.
    I’ve started with

    var $title = $("#gallery a img").attr("title");
    $("#gallery a").attr({
    title: $title,
    rel: 'gallery-set'
    });

    But this is setting the title for all the a tags to ‘piece number 3’, the title from the first image.

    #82792
    wolfcry911
    Participant

    the .attr method will get the attribute from only the first element in the selection

    there may be a better way, but I believe this works:

    $('#gallery a').each(function(){
    imgtitle = $(this).children('img').attr('title'),
    $(this).attr('title',imgtitle);
    });
    #82793
    DogsGhost
    Member

    Yep, that’s working. I figured I had to assign the variable as you did but just wasn’t sure where to work it in. Thanks for the help.

    #82794
    wolfcry911
    Participant

    your comment just made me realize you don’t even need the variable

    $('#gallery a').each(function(){
    $(this).attr('title',$(this).children('img').attr('title'));
    });

    This will work (not throw an error) even if the anchor has no image as a child, or has a different child element, or the image has no title…

Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.