开发者

remove parent element but keep the child element using jquery in HTML

From th开发者_StackOverflow中文版e below HTML i want to remove the div and H2 tags but keep the UL tag using jquery.

Please advise how i can achieve this

<div class="row">
    <h2><asp:Literal ID="categoryTitle" runat="server"></asp:Literal></h2>
    <ul class="tree js-catTree" id="treeContainer" runat="server"></ul>
</div>

Thanks


You can use replaceWith()

$('.row').replaceWith(function() {
 return $('ul', this);
});

Working Demo


I stumbled across this page when simply trying to remove a parent element (whilst still keeping the children) - just in case it's useful to others I found unwrap to be exactly what I needed. For me it was a simple find-an-element-and-unwrap:

$('.target-child').unwrap();

However the addition of the h2 removal in this case makes things a little bit more involved:

$('.row h2').siblings('ul').unwrap().end().remove();

http://jsfiddle.net/t8uQ8/

The above should be more optimal as it doesn't rely on the use of an anonymous function creation and call.


You could use jQuery detach() function ?

This will remove the element (visually) but keep its code in a variable, then you can append it into another parent.


As @Silvain said, you could detach the element and save the reference to a variable.

var $ul = $('.row h2').siblings('ul').detach();

Then you could insert the ul after its parent and, later, remove the parent from DOM:

$('.row').after($ul).remove();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜