I wanted to insert a li tag in the middle of a list of li tags based on a css class set to the li tag using jQuery. Consider the following
<ul class="myList">
<li><a href="#">test 1</a></li>
<li class="active"><a href="#">test 2</a></li>
<li><a href="#">test 3</a></li>
<li><a href="#">test 4</a></li>
<li><a href="#">test 5</a></li>
<li><a href="#">test 6</a></li>
</ul>
I wanted to insert a new li tag after the li tag set to active. So the output will be like this.
<ul class="myList">
<li><a href="#">test 1</a></li>
<li class="active"><a href="#">test 2</a></li>
<li><a href="#">My new Tag</a></li>
<li><a href="#">test 3</a></li>
<li><a href="#">test 4</a></li>
<li><a href="#">test 5</a></li>
<li><a href="#">test 6</a></li>
</ul>
I tried with .appendTo, .insertAfter, .append etc. but could not get the result I wanted. Any idea how this can be achieved?
The <li> HTML element is used to represent an item in a list. It must be contained in a parent element: an ordered list ( <ol> ), an unordered list ( <ul> ), or a menu ( <menu> ). In menus and unordered lists, list items are usually displayed using bullet points.
You can simply use the jQuery append() method to add <li> elements in an existing <ul> element. The following example will add a <li> element at the end of an <ul> on click of the button.
The <li> tag defines a list item. The <li> tag is used inside ordered lists(<ol>), unordered lists (<ul>), and in menu lists (<menu>). In <ul> and <menu>, the list items will usually be displayed with bullet points. In <ol>, the list items will usually be displayed with numbers or letters. Tip: Use CSS to style lists.
Unordered lists ( UL ), ordered lists ( OL ), and list items ( LI )
$('li.active').after('<li><a href="#">My new Tag</a></li>');
Try this:
$('<li><a href="#">content here</a></li>').insertAfter('ul.myList li.active');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With