Pregunta

On a page, I need to detect all the entries that have an image in them, and add styles to the H1 and img, and p that contains the img in those entries. No problem so far.

  <div class="entry">
    <h1>Headline</h1>
    <p><img></p>
  </div>

  $("div.entry img").closest(".entry").find("h1").addClass("home-h1-adjust");
  $("div.entry img").closest("p").addClass("home-p-img-adjust");

To fully solve the problem I'm facing, I need to detach either the h1 or p, and reinsert to where the p comes before the h1, and this is for a series of entries, not all of which have an image.

I'm getting stuck on the proper way to loop through and prepend the detached elements in jQuery. Thanks.

¿Fue útil?

Solución 4

Here was the solution that worked: iterate through all entries on the page, look for a image, attach the classes to the H1 and first p tag. Prepend the p containing the image above the H1, as the first child of the entry div.

  <div class="entry">
     <h1>Headline 1</h1>
     <p><img />Image? Yes</p>
     <p>Some Text that needs to stay put</p>
     <p>More copy text</p>
  </div>

  <div class="entry">
     <h1>Headline 2</h1>
     <p>Text in a non image entry</p>
     <p>This text has no image to keep it company</p>
  </div>


  $('div.entry').each(function(){
     var $this = $(this);
     if($this.find('img').length > 0) {
        $this.find('h1').addClass('home-h1-adjust');   
        var $img = $this.find('p').first().addClass('home-p-img-adjust');
        $this.prepend($img);
    }
  });

http://jsfiddle.net/lockedown/vkeeD/1/

Otros consejos

$('.entry > p').each(function() {
   $(this).insertBefore(this.previousElementSibling);
});

http://jsfiddle.net/Yr96v/

//for each entry
$('div.entry').each(function(){
    var $this = $(this);

    //if entry has img
    if($this.find('img').length > 0) {
        //jQuery is chainable, and detaching is done automatically
        $this.find('h1').addClass('home-h1-adjust')
            .before($this.find('p').addClass('home-p-img-adjust'));
    }
});

http://jsfiddle.net/tB8f4/

$('div.spacer a').addClass('test').each(
   function(){
       $(this).remove();
   }
);

You can use .each() just open your chrome console and play with it. the above example removes each related link on this page. of course you could do var element = $(this).detach(); and then element.appendTo('YOUR POSITION')

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top