css 如何在JavaScript中更改SVG路径的标题文本?

5f0d552i  于 2023-03-20  发布在  Java
关注(0)|答案(3)|浏览(168)

在我的HTML文件中,我有一个SVG,其路径语法如下:

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

如何使用JavaScript动态更改title text

368yc8dk

368yc8dk1#

document.querySelector与查询'#path0 > title'配合使用,查找作为#path0元素的直接后代的title元素。
使用path节点的textContent属性设置新的标题值。

const title = document.querySelector('#path0 > title');
title.textContent = 'I am a path';
<svg>
  <path id="path0">
    <title>title text</title>
  </path>
</svg>
nbysray5

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标记之间,如下所示:

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

希望能有所帮助。

vfwfrxfs

vfwfrxfs3#

使用document.querySelector选择路径内的标题。
'#path0>title'其中#选择具有值path0的ID,
>表示path0的直接子节点,
textContent给你多余的文本部分pf的标题。

document.querySelector('#path0>title').textContent = "New Content";

相关问题