gpt4 book ai didi

javascript - 如何在不更改 div 中的任何其他元素的情况下更改 div 中的文本

转载 作者:行者123 更新时间:2023-12-05 08:40:20 26 4
gpt4 key购买 nike

我有一个带有文本的 div 和一个用作其中链接的图标。我希望在单击按钮时更改文本而不影响图标。

innerHTML 和 innerText 都使图标消失。

<div class="title" id='title'>Text I want to change
<a href="https://link.com" target=_blank>
<img src="icon.svg"id='icon'>
</a>
</div>

<button id='button'>click here to change text<button>
function changeText(text) {
document.getElementById("title").innerText=text
}
const button = document.getElementById('button');
button.addEventListener('click', () => changeText('the new text I want'));

文本正确更改但图标消失。将图标移到 div 之外当然可以解决问题,但我不想这样做。非常感谢任何帮助。

最佳答案

使用 element.innerText() 实质上是覆盖了 div 的全部内容 - 包括其他 html 元素,例如 anchor 标记。

有一个子项附加到您的 div,它实际上包含您的文本。您可以通过 document.getElementById("title").firstChild 及其 .data 属性来引用它。

function changeText(text) {
document.getElementById("title").firstChild.data = text;
}
const button = document.getElementById('button');
button.addEventListener('click', () => changeText('the new text I want '));
<div class="title" id='title'>Text I want to change
<a href="https://link.com" target=_blank><img src="icon.svg" id='icon'></a>
</div>

<button id='button'>click here to change text<button>

关于javascript - 如何在不更改 div 中的任何其他元素的情况下更改 div 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56140202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com