Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

From the 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

like image 898
Amit Avatar asked May 09 '11 12:05

Amit


People also ask

Can we get the children element from the parent element using jQuery?

jQuery children() method is used to get the direct children of the selected HTML element. You can use children() method to traverse through the child elements of the selected parent element.

What is the use of parent () and child () method in jQuery?

The ("parent > child") selector selects all elements that are a direct child of the specified element.

Which jQuery method is used to remove the child elements from the selected element?

The jQuery empty() method removes the child elements of the selected element(s).


2 Answers

You can use replaceWith()

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

Working Demo

like image 194
Town Avatar answered Sep 24 '22 17:09

Town


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.

like image 34
Pebbl Avatar answered Sep 26 '22 17:09

Pebbl