如何使用JavaScript获取div元素的最后一个类名?
获取DOM元素最后一个类名的解决方案
针对你要获取每个带.ws-compid类的div最后一个类名的需求,有两种简单的实现方式:
方法一:直接利用DOMTokenList的类数组特性
DOMTokenList本身是类数组对象,支持通过索引访问元素,同时提供length属性,因此可以直接通过length - 1的索引获取最后一个类名:
[...document.querySelectorAll('.ws-compid')].map(component => { // 处理元素没有类名的边界情况 if (!component.classList.length) return null; return { id: component.innerText, type: component.classList[component.classList.length - 1] }; });
方法二:转换为数组后使用数组方法
把DOMTokenList解构为普通数组,就能使用数组的pop()或at(-1)方法直接获取最后一个元素:
[...document.querySelectorAll('.ws-compid')].map(component => { const classNames = [...component.classList]; if (!classNames.length) return null; return { id: component.innerText, type: classNames.at(-1) // 或者 classNames.pop() }; });
说明:DOMTokenList并没有内置的last()方法,所以直接调用会报错,上述两种方法都能解决这个问题,根据你的习惯选择即可。
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

