您好我正在尝试更新以下脚本的innerHTML
<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>
我试过以下
var cls =document.getElementById("global-alert-queue").getElementsByClassName("animate-in")[0].innerHTML = "Change Text";
但它不起作用。
答案 0 :(得分:1)
请参阅内联评论:
// Run when document is completely rendered and is ready to be manipulated
document.addEventListener("DOMContentLoaded", function () {
document.querySelector("#global-alert-queue .animate-in").innerHTML = "Change Text";
});
演示:http://jsfiddle.net/tusharj/kg3cc4gw/3/
<强> querySelector 强>
返回文档中的第一个元素(使用文档节点的深度优先预先遍历遍历),与指定的选择器组匹配。
有关querySelector
的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
答案 1 :(得分:0)
似乎工作正常。也许你应该将你的脚本移到HTML下面。或检查文件准备好了。
var cls =document.getElementById("global-alert-queue").getElementsByClassName("animate-in")[0].innerHTML = "Change Text";
&#13;
<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>
&#13;
答案 2 :(得分:0)
您需要删除var cls=...
。这是一个有效的jsFiddle。
答案 3 :(得分:0)
您可以使用Text添加按钮作为字符串,然后获得输出Demo HTML
function changeText() {
var cls = document.getElementById("global-alert-queue").getElementsByClassName("animate-in")[0].innerHTML = 'Change Text <button id="dismiss-alert" class="dismiss" type="button" onclick="changeText()">Change</button>';
}
<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>
答案 4 :(得分:0)
根据您的更新要求(Expected is "Change Text" should replace "Your submission was successful."
)
您无法更新animate-in
的内部html,因为它也会删除按钮元素。
因此,一个解决方案是仅更新animate-in
的第一个子节点,它是包含值的文本节点,如
document.querySelector("#global-alert-queue .animate-in").firstChild.nodeValue = "Change Text";
另一种方法是更新标记以将文本包装在另一个元素中,如
document.querySelector("#global-alert-queue .animate-in > span").innerHTML = "Change Text";
&#13;
<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>
&#13;