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

如何从多个select2-selection__choice类li元素的title属性构建数组?

实现方法:提取指定li元素的title属性为数组

当然可以实现!这是前端开发里很常见的DOM数据提取需求,不管你用原生JavaScript还是jQuery都能轻松搞定,下面给你两种实用的实现方案:

方案一:原生JavaScript实现

不需要依赖任何外部库,直接用浏览器原生API就能完成:

// 选中所有class为select2-selection__choice的li元素
const choiceElements = document.querySelectorAll('li.select2-selection__choice');
// 转换为数组并提取每个元素的title属性
const titleArray = Array.from(choiceElements).map(element => element.getAttribute('title'));

// 打印结果验证
console.log(titleArray);

说明:

  • document.querySelectorAll() 会返回所有匹配选择器的元素(一个NodeList集合)
  • Array.from() 把NodeList转换成可遍历的普通数组
  • map() 遍历数组中的每个元素,提取对应的title属性值,最终生成目标数组

方案二:jQuery实现(如果项目已引入jQuery)

如果你的项目里已经在用jQuery,代码会更简洁:

// 选中目标元素,提取title属性并转为普通数组
const titleArray = $('li.select2-selection__choice').map(function() {
  return $(this).attr('title');
}).get();

// 打印结果验证
console.log(titleArray);

说明:

  • jQuery的map()方法会遍历匹配到的元素集合,返回包含所有title值的jQuery对象
  • 最后调用get()方法把jQuery对象转换成普通JavaScript数组

这两种方法都能处理任意数量的目标li元素,不管title值是否重复,都会完整提取并整理成数组~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:32:50