skip to Main Content

In my HTML file, I have an SVG with the following path syntax:

<path id="path0">
    <title>title text</title>
</path>

Using JavaScript, how do I dynamically change title text?

3

Answers


  1. Use document.querySelector with the query '#path0 > title' to find the title element that is a direct descendant of the #path0 element.

    Use the textContent property of the path node to set a new title value.

    const title = document.querySelector('#path0 > title');
    title.textContent = 'I am a path';
    <svg>
      <path id="path0">
        <title>title text</title>
      </path>
    </svg>
    Login or Signup to reply.
  2. Use document.querySelector to select title inside path.
    '#path0>title' where # select id with value path0,
    > means direct child of path0,
    textContent gives you excess to the text portion pf title.

    document.querySelector('#path0>title').textContent = "New Content";
    
    Login or Signup to reply.
  3. First you have to select the parent, and may be save to a variable:

    const parent = document.getElementById('path0');

    Then you have to get the inside element what’s called a children:

    const children = parent.children[0];

    Or this in one step:

    const childElement = document.getElementById('path0').children[0];

    Then you can change the text inside it like this:

    childElement.textContent = "Your text here!";

    An other more coincise one liner version would look like this:

    document.querySelector('#path0>title').textContent = "Your text here!";

    Here you select the direct descendant of the lement marked with id="path0", then you change the text content whit the .textContent command. Note that in this case you don’t need to use a variable.

    You can insert your chosen code in the end of your html file between script tags like this:

    //...html  content
    <script>
      document.querySelector('#path0>title').textContent = "Your text here!";
    </script>
    

    I hope it helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search