jQuery move node out of its parent

坚强是说给别人听的谎言 提交于 2020-01-09 07:59:47

问题


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>

回答1:


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);
})



回答2:


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

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




回答3:


Try this:

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

See it in action here.



来源:https://stackoverflow.com/questions/6383941/jquery-move-node-out-of-its-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!