Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery move node out of its parent

I have this code:

<ul class="list">
  <li>
    <a href="#" >
      <img src="IMAGE" />
      SOME TEXT
    </a>
  </li>
  <li>
    <a href="#" >
      <img src="ANOTHER IMAGE" />
      SOME DIFFERENT TEXT
    </a>
  </li>
</ul>

I want the images prepended to the parent node like this:

<ul class="list">
  <li>
    <img src="IMAGE" />
    <a href="#" >
      SOME TEXT
    </a>
  </li>
  <li>
    <img src="ANOTHER IMAGE" />
    <a href="#" >
      SOME DIFFERENT TEXT
    </a>
  </li>
</ul>
like image 967
YeppThat'sMe Avatar asked Jun 17 '11 09:06

YeppThat'sMe


3 Answers

Try this:

$('.list > li > a > img').each(function() {
    $(this).insertBefore($(this).parent());
})

Demo at http://jsfiddle.net/alnitak/3nEVz/

EDIT I came up with a cleaner version:

$('.list > li > a > img').each(function() {
    $(this).parent().before(this);
})
like image 71
Alnitak Avatar answered Nov 02 '22 15:11

Alnitak


$('ul.list img').each(function(_, elem) {
    var $elem = $(elem);
    $elem.prependTo( $elem.closest('li') );
});

demo: http://jsfiddle.net/hPbZD/1/

like image 44
jAndy Avatar answered Nov 02 '22 16:11

jAndy


Try this:

$(function() {
    $('ul.list > li > a > img').each(function() {
      $(this).closest('li').prepend(this);
    });
});

See it in action here.

like image 34
Luke Bennett Avatar answered Nov 02 '22 16:11

Luke Bennett