Я думаю, что многие другие ответы пренебрегают, чтобы дать вам совет, как настроить SVG, чтобы вы могли позже легко найти свой текстовый элемент.
Обычный способ сделать это - датьтекстовый элемент id
атрибут.Затем вы можете найти его, позвонив по номеру getElementById()
.
var textElem = document.getElementById("mytext");
textElem.textContent = "1234";
<svg>
<text id="mytext" y="100">Test Content</text>
</svg>
Существуют и другие способы пометить свой элемент.Вы можете сделать это по class
:
var allTextElems = document.getElementsByClassName("mytext");
for (var i=0; i< allTextElems.length; i++) {
allTextElems.item(i).textContent = "1234";
};
<svg>
<text class="mytext" y="75">Test Content</text>
<text class="notmytext" y="100">Test Content</text>
<text class="mytext" y="125">Test Content</text>
</svg>
Или вы можете сделать это, используя атрибут data
:
var allTextElems = document.querySelectorAll('[data-key=mytext]');
allTextElems.forEach(function(item) {
item.textContent = "1234";
});
<svg>
<text data-key="mytext" y="75">Test Content</text>
<text data-key="notmytext" y="100">Test Content</text>
<text data-key="mytext" y="125">Test Content</text>
</svg>
Если по какой-то причине вы не можете изменить SVG, то следующим очевидным решением будет найти текстовый элемент, используя его положение в дереве DOM относительнок другим элементам.
// Select the first text element in the group which has class="two"
var textElem = document.querySelector("g.two text:first-child");
textElem.textContent = "1234";
<svg>
<g class="one">
<text y="50">Text in group 1</text>
</g>
<g class="two">
<text id="mytext" y="100">Test Content</text>
<text y="125">Other text in group 2</text>
</g>
</svg>
Если вы не знаете, где в файле будет находиться целевой текст, вы будете знать только, что в нем содержится, тогда вам нужно будет выполнить поиск по всемтекстовые элементы, чтобы найти правильный текст.
// Select the SVG we want to search
// (This is an example of what you would need to do if you had more than one svg on the page)
var mySvg = document.querySelector("#mysvg");
// Find all the text elements in that svg
var allTextElems = document.querySelectorAll("text");
// Check all the text elements found, and if they contain our text
// then replace it with the new text.
allTextElems.forEach(function(item) {
if (item.textContent === "Test Content") {
item.textContent = "1234";
}
});
<svg id="mysvg">
<g class="one">
<text y="50">Text in group 1</text>
</g>
<g class="two">
<text id="mytext" y="100">Test Content</text>
<text y="125">Other text in group 2</text>
</g>
</svg>