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

如何为未设置role="img"的SVG元素添加指定类?

给未设置role="img"的SVG元素添加类

要选择所有没有role="img"属性的SVG元素,你需要使用CSS的:not()伪类选择器——querySelectorAll接受的是CSS选择器语法,而非JS的逻辑运算符!,这也是你之前尝试失败的原因。

实现代码

const nonImgRoleSvg = document.querySelectorAll('svg:not([role="img"])');

nonImgRoleSvg.forEach(el => {
  el.classList.add("my--class");
});

代码说明

  • svg:not([role="img"]):该选择器会匹配所有SVG元素,自动排除其中带有role="img"属性的元素。
  • 遍历选中的元素集合,给每个元素添加目标类my--class。

如果需要同时区分两种SVG元素(分别添加不同类),可以一次性获取所有SVG元素后判断,减少DOM查询次数:

const allSvg = document.querySelectorAll('svg');

allSvg.forEach(el => {
  if (el.getAttribute('role') === 'img') {
    el.classList.add("img-role-class");
  } else {
    el.classList.add("my--class");
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:39:20