Javascript修改div类中的文本

时间:2015-06-16 06:30:40

标签: javascript html

您好我正在尝试更新以下脚本的“您的提交成功。”,并使用以下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>

它将按钮类替换为文本。我可以只替换文字吗?

2 个答案:

答案 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";
}

此处演示:http://jsfiddle.net/v9fmzLpx/