How to replace the value of the text element in svg from jquery

Roobena picture Roobena · Jul 16, 2014 · Viewed 9.1k times · Source

I am creating an svg tool for the constructing a building , i had created a room ( with the rect tool ) and grouped it and now want to place the name for that room eg : "Office" for the first time the text placed inside the rect , but for the next time i have to replace the name already exit inside the text element . Below is my code

    var svgns = 'http://www.w3.org/2000/svg';     
    var ex_x=70;
    var ex_y=30;

    var hidden = parseInt($("#svg_group_osiz_1").val());    
    var gethide_curtselid=$("#hide_curtselid").val();      
    var gethide_curtselid12=$("#hide_curtdrawx_id").val();     
    var gethide_curtselid13=$("#hide_curtdrawy_id").val();       

    var x=parseInt(gethide_curtselid12) + parseInt(ex_x);  
    var y=parseInt(gethide_curtselid13) + parseInt(ex_y);            

    var text = document.createElementNS(svgns, 'text');  

    text.setAttributeNS(null, 'x', x); 
    text.setAttributeNS(null, 'y', y);           
    text.setAttributeNS(null, 'fill', '#343938');    
    text.setAttributeNS(null, 'text-anchor', 'middle');
    text.textContent =room_name;    

    var html =$( "#"+gethide_curtselid ).html();        

    if(html.contains("</text>"))
    {       
        var start_string=html.indexOf("<text");
        var end_string  =   html.indexOf("</text>");        
        end_string      =   end_string+7;   
        remove_string   =   html.substring(start_string,end_string);        
        var content_replaced = html.replace(remove_string,"");      

        $( "#"+gethide_curtselid ).html(content_replaced);
        var replaced_html =$( "#"+gethide_curtselid ).html();   

    }   

    $( "#"+gethide_curtselid ).append(text);            

Here i had find whether the text is already present in the group and replace it as empty and again append the text, But it do-sent work. Can any one guide

Answer

T J picture T J · Jul 16, 2014

Try setting an id for the textNode

var text = document.createElementNS(svgns, 'text');  
text.setAttributeNS(null, 'x', x); 
text.setAttributeNS(null, 'y', y);           
text.setAttributeNS(null, 'fill', '#343938');    
text.setAttributeNS(null, 'text-anchor', 'middle');
text.setAttributeNS(null, 'id', 'roomName');
text.textContent =room_name; 

Then you can manipulate it using js like

document.getElementById('roomName').textContent = "new text";