如何使用JavaScript查找带有自定义属性wcmcode的HTML元素
解决方法
你可以直接使用CSS属性选择器语法,传入document.querySelector或者document.querySelectorAll即可实现按自定义属性筛选元素。
常用匹配场景如下:
- 匹配所有带有
wcmcode属性的img元素:document.querySelectorAll('img[wcmcode]') - 匹配
wcmcode属性值等于指定值的img元素(比如要找值为2的元素):// 取第一个匹配的元素 document.querySelector('img[wcmcode="2"]') // 取所有匹配的元素,替换为querySelectorAll即可 document.querySelectorAll('img[wcmcode="2"]') - 匹配
wcmcode属性值以指定内容开头的img元素(比如以1开头):document.querySelectorAll('img[wcmcode^="1"]') - 匹配
wcmcode属性值以指定内容结尾的img元素(比如以3结尾):document.querySelectorAll('img[wcmcode$="3"]') - 匹配
wcmcode属性值包含指定内容的img元素(比如包含2):document.querySelectorAll('img[wcmcode*="2"]')
使用示例:
// 获取wcmcode为3的图片并打印src属性 const targetImg = document.querySelector('img[wcmcode="3"]'); console.log(targetImg.src); // 输出 img3
内容的提问来源于stack exchange,提问作者cucuru
相关产品推荐
相关产品推荐

