You need to enable JavaScript to run this app. 如何使用原生JavaScript对HTML元素按字母顺序排序
优惠活动
大模型
产品
解决方案
定价
更多

如何使用原生JavaScript对HTML元素按字母顺序排序

动物卡片按名称字母排序原生JS实现方案

你可以直接使用以下原生JavaScript代码实现需求,无需引入jQuery等第三方库:

// 获取动物卡片父容器
const animalContainer = document.querySelector('.animal-container');
// 取出所有动物卡片并转为数组,方便调用排序方法
const animalCardList = Array.from(animalContainer.querySelectorAll('.animal-cards'));

// 按动物名称字母顺序排序
animalCardList.sort((cardA, cardB) => {
  // 提取两张卡片的动物名称文本,去除首尾空格避免干扰
  const nameA = cardA.querySelector('.animal-name').textContent.trim();
  const nameB = cardB.querySelector('.animal-name').textContent.trim();
  // 按自然字母顺序比较,配置sensitivity: 'base'可实现大小写不敏感排序
  return nameA.localeCompare(nameB, undefined, { sensitivity: 'base' });
});

// 将排序后的卡片依次插入容器,原有元素会自动被移动不会重复生成
animalCardList.forEach(card => animalContainer.appendChild(card));

针对你提供的示例HTML,运行上述代码后,卡片会自动按 Camel → Dog → Giraffe → Lion 的字母顺序排列。
如果需要严格区分大小写排序,删除localeCompare的第三个参数即可。

内容的提问来源于stack exchange,提问作者billyPeltzer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 02:24:03