I'm trying to insert an li element into a specific index on a ul element using jQuery. I only seem to be able to insert an element on the end of the list. I am very new to jQuery, so I may just not be thinking properly.
First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the append() method to copy the element as its child.
jQuery insertAfter() Method The insertAfter() method inserts HTML elements after the selected elements. Tip: To insert HTML elements before the selected elements, use the insertBefore() method.
jQuery hide() Method The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page).
jQuery uses: . append(); and . remove(); functions to accomplish this task. We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.
Try something like this:
$("#thelist li").eq(3).after("<li>A new item</li>");
With the eq
function, you can get a specific index of the elements retrieved...then, insert the new list item after it.
In the above function, I am inserting a new item at position 4 (index 3).
More info about the function at the jQuery Docs
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