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

如何使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:24:05