javascript jQuery 将节点移出其父节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6383941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:27:39 来源:igfitidea点击:
jQuery move node out of its parent
提问by YeppThat'sMe
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>
回答by Alnitak
Try this:
试试这个:
$('.list > li > a > img').each(function() {
$(this).insertBefore($(this).parent());
})
Demo at http://jsfiddle.net/alnitak/3nEVz/
演示在http://jsfiddle.net/alnitak/3nEVz/
EDITI came up with a cleaner version:
编辑我想出了一个更干净的版本:
$('.list > li > a > img').each(function() {
$(this).parent().before(this);
})
回答by jAndy
$('ul.list img').each(function(_, elem) {
var $elem = $(elem);
$elem.prependTo( $elem.closest('li') );
});