skip to Main Content

I want to select text tag. I have tried different methods. This is a part of a bigger problem. I want to select the text tag and append it. there are multiple elements of tag I want the specific the bottom one and I cannot do any changes in SVG code as it is created by Google API So I have to do all changes by JS

var gElement = document.querySelector('#chart_div svg > g:nth-child(9)');
var svg = document.getElementById("chart_div").getElementsByTagName("svg")[0];
var eighthGText = svg.getElementsByTagName("g")[7].getElementsByTagName("text")[0];
<div id="chart_div">
  <div>
    <div>
      <svg width="800" height="600">
        <defs></defs>
        <g></g>
        <g> <text></text></g>
        <g></g>
        <g></g>
        <g></g>
        <g></g>
        <g></g>
        <g>
          <text></text>
        </g></svg>
    </div>
  </div>
</div>

var svg = document.getElementById("chart_div").getElementsByTagName("svg")[0];
var eighthGText = svg.getElementsByTagName("g")[7].getElementsByTagName("text")[0];
var gElement = document.querySelector(‘#chart_div svg > g:nth-child(9)’);

2

Answers


  1. You select it the same way you would any other element, eg. document.querySelector('text').

    Here’s a working example. Note the use of x and y attributes on the text element to ensure it’s actually visible – which may in fact be your actual problem.

    document.querySelector('text').textContent = 'Lorem ipsum';
    <div id="chart_div">
      <div>
        <div>
          <svg width="800" height="600">
            <defs></defs>
            <g></g>
            <g></g>
            <g></g>
            <g></g>
            <g></g>
            <g></g>
            <g></g>
            <g>
              <text x="50" y="50"></text>
            </g>
          </svg> <!-- note that this tag was missing in your original -->
        </div>
      </div>
    </div>
    Login or Signup to reply.
  2. The fucntion TestIt() will display the text inside the specific text tag…

    <!DOCTYPE html>
    <head>
    </head>
    
    <body onload="TestIt();">
    
    <script type="text/javascript">
    
    //----------------------------------------
    
    function TestIt(){
    
    let e=chart_div;
    
    let g=e.getElementsByTagName('g');
    
    g=g[g.length-1];
    
    let t=g.getElementsByTagName('text')[0];
    
    alert(t.textContent);
    
    }
    
    //----------------------------------------
    
    </script>
    
    <div id="chart_div">
      <div>
        <div>
          <svg width="800" height="600">
            <defs></defs>
            <g></g>
            <g> <text></text></g>
            <g></g>
            <g></g>
            <g></g>
            <g></g>
            <g></g>
            <g>
              <text>sample text</text>
            </g></svg>
        </div>
      </div>
    </div>
    
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search