add li to middle of the ul (jquery)

不问归期 提交于 2020-01-10 19:39:14

问题


How one can add li to middle of the ul.

For example if i have list like this:

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

And i want to add addiion li (<li>new</li>) after 3rd list?


回答1:


var middle = Math.ceil($("#myUL li").length / 2);
$("#myUL li:nth-child(" + middle + ")").after('<li>Item New</li>');



回答2:


Try this out:

$('ul li:nth-child(3)').after('<li>new</li>');



回答3:


Try this:

$('ul li:eq(2)').after(`<li>new</li>`)

Use ' or " within braces I have used ` since it was getting formatted as html.



来源:https://stackoverflow.com/questions/2269013/add-li-to-middle-of-the-ul-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!