Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert a new li tag at the specified location?

Tags:

jquery

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?

like image 606
Amit Avatar asked Apr 05 '10 11:04

Amit


People also ask

How to use li tag in HTML?

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.

How do you insert Li?

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.

What are ul and li tag in HTML?

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.

What does li mean in HTML?

Unordered lists ( UL ), ordered lists ( OL ), and list items ( LI )


2 Answers

$('li.active').after('<li><a href="#">My new Tag</a></li>');
like image 149
Matthew Flaschen Avatar answered Oct 09 '22 10:10

Matthew Flaschen


Try this:

$('<li><a href="#">content here</a></li>').insertAfter('ul.myList li.active');
like image 2
Sarfraz Avatar answered Oct 09 '22 11:10

Sarfraz