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

通过类名在HTML元素中加载SVG代码:无法选中多个同类元素

解决多元素插入SVG图标的问题

你的核心问题是:getElementsByClassName和querySelectorAll返回的是元素集合而非单个元素,不能直接对集合使用innerHTML,必须遍历每个元素逐个操作。

方案1:使用getElementsByClassName + 遍历

getElementsByClassName返回HTMLCollection(类数组对象),可以转成数组后用forEach,或直接用for循环:

// 转数组后forEach遍历
const plusElements = document.getElementsByClassName("plus");
Array.from(plusElements).forEach(element => {
  element.innerHTML += '<svg viewBox="0 0 28 28"><polygon points="28,12.5 15.5,12.5 15.5,0 12.5,0 12.5,12.5 0,12.5 0,15.5 12.5,15.5 12.5,28 15.5,28 15.5,15.5 28,15.5 "/></svg>';
});

// 或者用for循环(兼容更旧浏览器)
const plusElements = document.getElementsByClassName("plus");
for (let i = 0; i < plusElements.length; i++) {
  plusElements[i].innerHTML += '<svg viewBox="0 0 28 28"><polygon points="28,12.5 15.5,12.5 15.5,0 12.5,0 12.5,12.5 0,12.5 0,15.5 12.5,15.5 12.5,28 15.5,28 15.5,15.5 28,15.5 "/></svg>';
}

方案2:使用querySelectorAll + forEach

querySelectorAll返回NodeList,现代浏览器支持直接调用forEach:

// 直接使用forEach
const plusElements = document.querySelectorAll(".plus");
plusElements.forEach(element => {
  element.innerHTML += '<svg viewBox="0 0 28 28"><polygon points="28,12.5 15.5,12.5 15.5,0 12.5,0 12.5,12.5 0,12.5 0,15.5 12.5,15.5 12.5,28 15.5,28 15.5,15.5 28,15.5 "/></svg>';
});

// 用模板字符串优化可读性(推荐)
const plusSvg = `
<svg viewBox="0 0 28 28">
  <polygon points="28,12.5 15.5,12.5 15.5,0 12.5,0 12.5,12.5 0,12.5 0,15.5 12.5,15.5 12.5,28 15.5,28 15.5,15.5 28,15.5 "/>
</svg>
`;

document.querySelectorAll(".plus").forEach(el => {
  el.innerHTML += plusSvg;
});

注意事项

  • 如果需要兼容极旧浏览器(如IE),可以给NodeList手动添加forEach支持,或者转成数组:Array.from(plusElements).forEach(...)
  • 模板字符串(反引号包裹)可以保留SVG的换行格式,让代码更易维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 07:43:13