是否有办法从<svg>
中删除<defs>
元素与纯javascript或jquery?
我找到了d3库的解决方案,但我想避免为此添加整个库。
使用ChildNode.remove()删除元素,并将所需的选择器传递给querySelector
document.querySelector("defs").remove();
<svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Some graphical objects to use -->
<defs>
<circle id="myCircle" cx="0" cy="0" r="5" />
<linearGradient id="myGradient" gradientTransform="rotate(90)">
<stop offset="20%" stop-color="gold" />
<stop offset="90%" stop-color="red" />
</linearGradient>
</defs>
<!-- using my graphical objects -->
<use x="5" y="5" xlink:href="#myCircle" fill="url('#myGradient')" />
</svg>
对于多个元素使用querySelectorAll和NodeList.forEach:
document.querySelectorAll("defs").forEach(EL => EL.remove());