首页 > 解决方案 > 如何在不更改子元素的情况下更改元素 innerText

问题描述

我有一个 html 元素,例如:

<div id="el1">Change only me<div>but not me</div></div>

但我只想更改第一个文本并保留子 div 原样

document.getElementById("el1").innerText = "changed!"
<div id="el1">Change only me<div>but not me</div></div>

标签: javascripthtmlparent-childinnertext

解决方案


尝试这个:

document.getElementById("el1").childNodes[0].textContent = "changed";
<div id="el1">Change only me<div>but not me</div></div>


推荐阅读