简体   繁体   中英

Add g tag into svg tag without jquery

I have svg element from this code

let chartSVG = ReactDOM.findDOMNode(this.refChart).children[0];

I want to add a watermark contain g tag into that chartSVG.

Should be basic DOM manipulation using createElementNS and appendChild() :

 const xmlns = "http://www.w3.org/2000/svg"; const rect = document.createElementNS(xmlns, 'rect'); rect.setAttributeNS (null, "width", 50); rect.setAttributeNS (null, "height", 50); const g = document.createElementNS(xmlns, 'g'); g.appendChild(rect); const svg = document.getElementById('svg'); svg.appendChild(g);
 <svg id="svg"></svg>

Or, if you have your SVG content as a string, you can use a DOMParser() and import the fragment:

 const g = new DOMParser().parseFromString( '<g xmlns="http://www.w3.org/2000/svg"><rect width="50" height="50"/></g>', 'application/xml'); const svg = document.getElementById('svg'); svg.appendChild(svg.ownerDocument.importNode(g.documentElement, true));
 <svg id="svg"></svg>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM