user1570775
user1570775

Reputation: 43

How to remove nested UL element but keep child elements

I wish to remove the <ul> tags for a nested list and then add its child <li> elements to the parent <ul> element. For example :

<ul>
    <li>Item 1</li>
    <ul>
        <li>Item 2</li>
    </ul>
    <li>Item 3</li>
</ul>

Should become :

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

I am new to jQuery and what I have created so far is not working and I am not sure why:

 $content.find('ul').each(function() {
if ($(this).parent().is('li')) {
  var elements = $(this).children().detach();
  var closest = $(this).closest('li');
  $(this).remove();
  elements.appendTo(closest);
}
}

Any help much appreciated.

Upvotes: 3

Views: 601

Answers (2)

Bas Kuis
Bas Kuis

Reputation: 770

try

var elements = [];
$('ul.outer li').each(function(){
    elements.push(this); 
});
$('ul.outer').html('');
for(x in elements){
    $('ul.outer').append($(elements[x])[0].outerHTML);
}

if you need it to work for .. multiple levels deep .. for example

<ul class="outer">
<li>Item 1</li>
<ul>
    <li>Item 2</li>
    <ul>
        <li>Item 2</li>
    </ul>
</ul>
<li>Item 3</li>
</ul>

Upvotes: 1

use .unwrap()

DEMO or DEMO

$('ul > ul > li').unwrap('ul');

Upvotes: 6

Related Questions