如何使用jQuery将指定列表元素移动到目标元素的正下方?
Great question! You’re already comfortable using appendTo() and prependTo() for moving elements to the top or bottom of a container, but when you need to place an element immediately after a specific sibling, jQuery has two simple, effective methods to get this done: insertAfter() and after().
Example 1: Move #listI1 right after #listI2
Using insertAfter()
This method takes the target element as its argument and places the selected element immediately after it. It’s intuitive if you’re starting with the element you want to move:
$('#listI1').insertAfter('#listI2');
After running this, your list will update to:
<ul id="fruit"> <li id="listI2">apple</li> <li id="listI1">banana</li> <li id="listI3">orange</li> <li id="listI4">grape</li> <li id="listI5">strawberry</li> </ul>
Using after()
Alternatively, you can call after() on the target element and pass the element you want to move. This achieves the exact same result, just framed from the target’s perspective:
$('#listI2').after($('#listI1'));
Example 2: Move #listI1 right after #listI5
To place #listI1 directly below #listI5, just swap the target selector in either method:
// Using insertAfter() $('#listI1').insertAfter('#listI5'); // Or using after() $('#listI5').after($('#listI1'));
This will rearrange your list to:
<ul id="fruit"> <li id="listI2">apple</li> <li id="listI3">orange</li> <li id="listI4">grape</li> <li id="listI5">strawberry</li> <li id="listI1">banana</li> </ul>
Key Note
Both methods automatically remove the element from its original position before inserting it in the new location—you don’t need to manually detach or delete it first. This keeps your code clean and efficient.
内容的提问来源于stack exchange,提问作者Skullomania

