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
?
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
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.Use
document.querySelector
to select title inside path.'#path0>title'
where#
select id with valuepath0
,>
means direct child ofpath0
,textContent
gives you excess to the text portion pf title.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:
I hope it helps.