You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现无序列表首子元素为图片时调换前两个<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 querySelector with 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).
  • insertBefore handles 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:09:08