SVG Clear group<g>

SVG Clear group<g>

本文关键字:gt Clear lt SVG group      更新时间:2023-09-26

假设我有一个类似这样的svg元素

<svg id="svgCanvas" class="pan" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="none">
    <g id="viewport">
      //Filled with an arbitrary amount of lines and cirles - examples below.
     <line x1="632" y1="357.5" x2="682" y2="270.89745962155615" class="line" style="stroke: rgb(128, 128, 128); stroke-width: 1.3px;"></line>
     <circle cx="82.08376766398476" cy="367.0988235405059" r="16.5" stroke="blue" fill="white" class="circle"></circle>
    </g>
</svg>

如何清除该组中的所有内容,同时保留组元素本身?

只需使用DOM方法,不需要任何框架:

var el = document.getElementById("viewport");
while (el.firstChild) {
    el.removeChild(el.firstChild);
}
document.addEventListener('load', function(){
    document.getElementById("viewport").innerHTML = "";
});