Forums

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

Home Forums JavaScript JQuery – Using Image Attr to populate ‘caption’ paragraph

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #35984
    Eamonn
    Member

    Hi guys, I’m not (at all) familiar with JQuery and only dip my toe in once in a blue moon. However, I have a need that I simply cannot find a quick solution for – despite my conviction that such a quick solution must be available :)

    I have a div in which images may be floated amongst the text. I want to scan that div, select all the images (if any), append a

    to them, and enclose both and matching

    in their own wrapping div. Into that created paragraph block I then want to place the title attribute of said image.

    I’ve tried Google and StackOverflow, but both are coated with snippets dealing with plugins, whereas I just want a plug-and-play snippet I can place in my included js file. I have tried piecing together something myself, but it’s a mess.

    Any help at all greatly appreciated!

    #94068
    Eamonn
    Member

    Solved via StackOverflow:

    $("#yourdiv img").each(function() { //Loops through the images in a specific div. $(this) represents the current image in the loop
    $(this).addClass("yourclass"); //Add a class
    $(this).wrap("

    "); //Add a wrapping div
    $("

    ").text($(this).prop("title")).insertAfter($(this)); //Create a new paragraph with the title property of the image as text and put it after the image (inside our newly created div)
    });

    I’ve included this in the Snippets gallery

    #94070
    Chris Coyier
    Keymaster

    For HTML5 semantics, I’d wrap the image in a figure and put the caption in a figcaption:

    http://jsfiddle.net/chriscoyier/pyTre/

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