My goal is to strip the images and iframes out of WordPress posts (they are in .para
divs) and move them to a <ul>
above the post, just inside the local wrapper (.wrapper940
).
I have written this code, which as far as I can see should work. Any help very much appreciated.
jQuery("document").ready (function($){
// First I set up a conditional loop: if images or iframes are found in .para, do the following
if ( $(".para img, .para iframe").length > 0) {
// ... create the <ul>
var newUl = $("<ul></ul>");
// and move it to the desired location, just inside .wrapper940
newUl.prependTo($(this).parents(".wrapper940"));
// Now I start the loop for each image or iframe found
$(this).each(function() {
// For each one I create an <li> element.
var newLi = $("<li></li>");
// Now I put the li element into the <ul> that I created above
newLi.appendTo($(this).parents("newUl"));
// Last I put 'this' into the new <li>.
newLi.append(this);
});
});
});
I have created a jsfiddle here to show this in context with the html.
The html is:
<div class="news-item-wrap">
<div class="date">the date</div>
<div class="wrapper940">
<div class="title">the title</div>
<div class="para">
<p>The main content of the post.</p>
<p>Which could be several paragraphs</p>
<p>And include iframes...</p>
<p><iframe src="//www.youtube.com/embed/uGMbZNTym-g" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen">...</iframe>
</p>
<p>Followed by more text... and maybe some images....</p>
<p><a href="http://www.joujouka.org/wp-content/uploads/2014/05/festival-interculture.jpg"><img class="alignnone size-medium wp-image-404" alt="festival intercultural" src="http://www.joujouka.org/wp-content/uploads/2014/05/festival-interculture-213x300.jpg" width="213" height="300"/></a>
</p>
</div>
</div>
<div class="news-item-wrap">
<div class="date">the date</div>
<div class="wrapper940">
<div class="title">the title</div>
<div class="para">
<p>A second post would follow like this.</p>
<p>Which could also be several paragraphs</p>
<p>And include iframes...</p>
<p><iframe src="//www.youtube.com/embed/uGMbZNTym-g" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen">...</iframe>
</p>
<p>Followed by more text... and maybe some images....</p>
<p><a href="http://www.joujouka.org/wp-content/uploads/2014/05/festival-interculture.jpg"><img class="alignnone size-medium wp-image-404" alt="festival intercultural" src="http://www.joujouka.org/wp-content/uploads/2014/05/festival-interculture-213x300.jpg" width="213" height="300"/></a>
</p>
</div>
</div>
This would continue for as many posts as there were. So I need to be able to move the images and iframes FOR EACH POST to appear just inside the .wrapper940
that wraps EACH POST. (i.e. above the title of each post.) I think that using .parents()
is sending all images and iframes from all posts to the first .wrapper940
; .closest()
seems like it should work, but doesn't, maybe because it breaks the loop?