您好我正在尝试更新以下脚本的“您的提交成功。”,并使用以下javascript代码:
var cls = document.getElementById("global-alert-queue").getElementsByClassName("animate-in")[0].innerHTML = "Change Text";
<div id="global-alert-queue" class="layout-wrapper">
<div class="alert success animate-in" role="alert">
Your submission was successful.
<button id="dismiss-alert" class="dismiss" type="button"></button>
</div>
</div>
它将按钮类替换为文本。我可以只替换文字吗?
答案 0 :(得分:2)
更新animate-in
的内部html的问题是该元素中有一个您不想更改的按钮元素。
因此,您需要访问animate-in的第一个子节点,即要更新的文本节点。
document.querySelector("#global-alert-queue .animate-in").firstChild.nodeValue = "Change Text";
<div id="global-alert-queue" class="layout-wrapper">
<div class="alert success animate-in" role="alert">
Your submission was successful.
<button id="dismiss-alert" class="dismiss" type="button"></button>
</div>
</div>
或者更好的解决方案是将文本包装在另一个元素中并更新该元素,如
document.querySelector("#global-alert-queue .animate-in > span").innerHTML = "Change Text";
<div id="global-alert-queue" class="layout-wrapper">
<div class="alert success animate-in" role="alert">
<span>Your submission was successful.</span>
<button id="dismiss-alert" class="dismiss" type="button"></button>
</div>
</div>
答案 1 :(得分:1)
这样做:
<强> HTML 强>
<div id="global-alert-queue" class="layout-wrapper">
<div class="alert success animate-in" role="alert">
Your submission was successful.
<button id="dismiss-alert" class="dismiss" type="button" onClick="changeText()">Change</button>
</div>
</div>
<强>的Javascript 强>
function changeText() {
document.getElementsByClassName("animate-in")[0].firstChild.nodeValue = "Change Text";
}