Wrap li in another li

I have a list below. In which I want to wrap the last three li in another ul li tag.

My html

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

I want to

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

my code

$('ul li:not(:first)').wrap('<li></li>');

But he tears the personality into another. Help in search engines

+4
source share
2 answers

Everything you need here in this context .wrapAll()

Try

$('ul li:not(:first)').wrapAll('<li><ul></ul></li>');

Demo

+7
source

try it

for me to avoid: first pseudo class, because in many cases this does not work, so try running the code

 $(function(){

$('ul li').eq(0).addClass('hi');

$('li').not('.hi').wrapAll('<ul><li></li></ul>');

});
0
source

Source: https://habr.com/ru/post/1536564/


All Articles