简体   繁体   中英

Trying to append a svg text to existing svg element

I am trying to append a svg text using html document to a existing svg I have , but it doens't seem to work here is the code I use

        var clickedEle=document.getElementById('clicked');
        clickedEle.style.fill='orange';
        clickedEle.style.backgroundImage = "url('images/mayans.jpg')";
        var btnText=document.createElementNS(svgns,'text');
        var btnLine= document.createElementNS(svgns,'line');

        btnText.setAttribute('x',hexObj.cx);
        btnText.setAttribute('y',hexObj.cy);  //hex is the object referencing the svg
        btnText.textContent ="Some text";

I don't see anything inspite of the dom getting appended.I tried adding html element using foreingObject , also tried chaging the background image using css but the svg element I am trying to add to remains the same.

Fiddle: https://jsfiddle.net/Snedden27/6b0tx248/

Its line number 346, you have to click on one of the orange hexagons to see the hexagon I am trying to append to.

As Sasidhar pointed out, your code is adding the text element to a polygon element which is not a valid parent for a text element. You need to add the text element to the svg element. In the code where the text element is being added, the variable clickedEle is a polygon element and the variable hex is the svg element.

Change...

clickedEle.appendChild(btnText);

to...

hex.appendChild(btnText);

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