如何实现无序列表首子元素为图片时调换前两个<li>元素位置
Solution: Swap List Items When First is an Image
Got it, let's tackle this problem. You want to check if the first list item in an unordered list (<ul>) contains an image as its direct child, then swap its position with the second list item. Here's how you can implement this with vanilla JavaScript, plus a jQuery alternative if that's your preference.
Vanilla JavaScript Implementation
This works without any external libraries and handles edge cases like lists with only one item (so we don't throw errors):
// Grab all unordered lists on the page const allLists = document.querySelectorAll('ul'); // Loop through each list to check and modify allLists.forEach(list => { const firstListItem = list.querySelector('li:first-child'); const secondListItem = list.querySelector('li:nth-child(2)'); // Only proceed if both list items exist, and the first has an img as its direct child if (firstListItem && secondListItem && firstListItem.firstElementChild.tagName === 'IMG') { // Option 1: Move the second item to the first position list.insertBefore(secondListItem, firstListItem); // Option 2: Move the first item to the second position (same end result) // list.insertBefore(firstListItem, secondListItem.nextSibling); } });
Breakdown of the code:
document.querySelectorAll('ul')fetches every<ul>element on your page.- We grab the first and second list items using
querySelectorwith CSS pseudo-classes. - The condition checks that both items exist (so we don't try to swap when there's only one item) and that the first item's direct child is an
<img>(matching your example structure). insertBeforehandles the position swap — either approach (moving the second item forward or the first item back) will give you the desired order.
jQuery Alternative
If you're already using jQuery in your project, here's a concise version:
$('ul').each(function() { const $firstLi = $(this).find('li:first'); const $secondLi = $(this).find('li:eq(1)'); if ($firstLi.length && $secondLi.length && $firstLi.children('img').length) { $secondLi.insertBefore($firstLi); } });
This does the same check and swap, but uses jQuery's built-in methods to simplify the syntax.
内容的提问来源于stack exchange,提问作者Kuma
相关产品推荐
相关产品推荐

