簡體   English   中英

如何刪除嵌套的UL元素但保留子元素

[英]How to remove nested UL element but keep child elements

我希望刪除嵌套列表的<ul>標記,然后將其子<li>元素添加到父<ul>元素。 例如 :

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

應該成為:

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

我是jQuery的新手,到目前為止我創建的內容不起作用,我不確定原因:

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

任何幫助非常感謝。

使用.unwrap()

演示演示

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

嘗試

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

如果你需要它來工作...多層深...例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM