jQuery loop to create divs and append content to them

I am trying to create a jQuery loop that:

  1. searches through the WordPress post in question for any images or iframes
  2. creates a new div for each of these and inserts the image or iframe into the div
  3. reorders things visually so that these newly created and newly populated divs appear where I want them (in this case above the post and post title).

I am been trying for over a week to accomplish this, and have gotten close, but something is always wrong.

Read More
jQuery("document").ready (function(){
   jQuery(".para img, iframe").each(function(){
      jQuery(this).prependTo(jQuery(this).parents(".wrapper940"));

      var ndiv = jQuery("<div></div>");
      jQuery(ndiv).append(this);
   })
});

So in the above code, I search for any images or iframes within the .para class, then run an ‘each’ function on them to prepend them to the post’s parent (.wrapper940), and then once they’re up there I attempt to create a new div for each image/iframe.

With this particular version of the code, it simply doesn’t display images or iframes at all, so I assume I need to somehow ‘print’ the ndiv element? Have my images and iframes disappeared into a variable and so no longer show up?

Sorry for the roundabout and possibly overly specific post; I don’t know enough about what I’m dealing with to be able to ask a more pointed question.

Related posts

Leave a Reply

1 comment

  1. You are first prepending the img or iframe to your ‘.wrapper940’, but then immediately appending your img/iframe to a newly created div that is not connected to anything. Your very first operation is completely being undone by the second (by appending it to the div, you automatically remove it from the wrapper). I assume you actually want all your images and frames to be appended first to a new div item, and then that div item is the one that actually gets put into the wrapper…

    jQuery("document").ready (function(){
       jQuery(".para img, iframe").each(function(){
          // First I create the div element.
          var ndiv = jQuery("<div></div>");
    
          // Now I put the div element into the wrapper, instead of the 'this'
          ndiv.prependTo(jQuery(this).parents(".wrapper940"));
    
          // Last I put 'this' into the div.
          ndiv.append(this);
       })
    });