简体   繁体   中英

How to remove item from list with jquery?

I have an output with content like below

<ul>
    <li>
        Songs
        <ul>
             <li>
                 Genre
                 <ul>
                     <li>
                         Country
                     </li>
                 </ul>
             </li>
        </ul>
    </li>
</ul>
<ul>
    <li>
        Songs
        <ul>
             <li>
                 Genre
                 <ul>
                     <li>
                         Pop
                     </li>
                 </ul>
             </li>
        </ul>
    </li>
</ul>

Please ignore why the content is shown like that. My question is, how can I use jQuery to remove the repeating parents <li> and <ul> so it will look like this

<ul>
    <li>
        Songs
        <ul>
             <li>
                 Genre
                 <ul>
                     <li>
                         Country
                     </li>
                     <li>
                         Pop
                     </li>
                 </ul>
             </li>
        </ul>
    </li>
</ul>

I've tried unwrap() method, but don't know the logic to put the <li> where they should be.

Try,

var uls = $('ul');
uls.first().find('ul:last').append(uls.last().find('li:last'));
uls.first().siblings('ul').remove();

DEMO

I would get what I need and re-write it, assuming there is some sort of container around the entire thing just re-write the middle. Code could be cleaner but it works nice.

<div>
<ul>
    <li>
        Songs
        <ul>
             <li>
                 Genre
                 <ul>
                     <li>
                         Country
                     </li>
                 </ul>
             </li>
        </ul>
    </li>
</ul>
<ul>
    <li>
        Songs
        <ul>
             <li>
                 Genre
                 <ul>
                     <li>
                         Pop
                     </li>
                 </ul>
             </li>
        </ul>
    </li>
</ul>
</div>

<script>
var li='';
$.each($("li:contains('Genre') ul li"), function(i, e){
  item=$(e).children('ul').text().replace(/\n/g,'').trim()||'';
    if (item.length!=0){
        li+='<li>'+item+'</li>';
    };
});

if (li.length!=0){
    var html='<ul><li>Songs<ul><li>Genre<ul>'+li+'</ul></li></ul></li></ul>';
    $('div').html(html);
};
</script>

Demo: http://jsfiddle.net/886P3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM