Grow your CSS skills. Land your dream job.

inserting rel and title attr into anchor tags

  • # July 3, 2011 at 7:08 pm

    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.

    # July 3, 2011 at 9:21 pm

    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);
    });
    # July 3, 2011 at 9:30 pm

    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.

    # July 3, 2011 at 10:01 pm

    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)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".