在我的HTML文件中,我有一个SVG,其路径语法如下:
<path id="path0"> <title>title text</title> </path>
如何使用JavaScript动态更改title text?
title text
368yc8dk1#
将document.querySelector与查询'#path0 > title'配合使用,查找作为#path0元素的直接后代的title元素。使用path节点的textContent属性设置新的标题值。
document.querySelector
'#path0 > title'
#path0
textContent
const title = document.querySelector('#path0 > title'); title.textContent = 'I am a path';
<svg> <path id="path0"> <title>title text</title> </path> </svg>
nbysray52#
首先,您必须选择父对象,并可能保存到变量中:const parent = document.getElementById('path0');然后你必须得到一个叫做children的内部元素:const children = parent.children[0];或者一步到位:const childElement = document.getElementById('path0').children[0];然后,您可以像这样更改其中的文本:childElement.textContent = "Your text here!";另一个更精确的单内衬版本如下所示:document.querySelector('#path0>title').textContent = "Your text here!";这里你选择id=“path0”元素的直接后代,然后用.textContent命令改变文本内容,注意在这种情况下你不需要使用变量。您可以将所选代码插入到html文件末尾的script标记之间,如下所示:
const parent = document.getElementById('path0');
const children = parent.children[0];
const childElement = document.getElementById('path0').children[0];
childElement.textContent = "Your text here!";
document.querySelector('#path0>title').textContent = "Your text here!";
//...html content <script> document.querySelector('#path0>title').textContent = "Your text here!"; </script>
希望能有所帮助。
vfwfrxfs3#
使用document.querySelector选择路径内的标题。'#path0>title'其中#选择具有值path0的ID,>表示path0的直接子节点,textContent给你多余的文本部分pf的标题。
'#path0>title'
#
path0
>
document.querySelector('#path0>title').textContent = "New Content";
3条答案
按热度按时间368yc8dk1#
将
document.querySelector
与查询'#path0 > title'
配合使用,查找作为#path0
元素的直接后代的title元素。使用path节点的
textContent
属性设置新的标题值。nbysray52#
首先,您必须选择父对象,并可能保存到变量中:
const parent = document.getElementById('path0');
然后你必须得到一个叫做children的内部元素:
const children = parent.children[0];
或者一步到位:
const childElement = document.getElementById('path0').children[0];
然后,您可以像这样更改其中的文本:
childElement.textContent = "Your text here!";
另一个更精确的单内衬版本如下所示:
document.querySelector('#path0>title').textContent = "Your text here!";
这里你选择id=“path0”元素的直接后代,然后用.textContent命令改变文本内容,注意在这种情况下你不需要使用变量。
您可以将所选代码插入到html文件末尾的script标记之间,如下所示:
希望能有所帮助。
vfwfrxfs3#
使用
document.querySelector
选择路径内的标题。'#path0>title'
其中#
选择具有值path0
的ID,>
表示path0
的直接子节点,textContent
给你多余的文本部分pf的标题。