Hi I am trying to update the innerHTML of following script
See the comments inline:
// 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";
});
Demo: http://jsfiddle.net/tusharj/kg3cc4gw/3/
querySelector
Returns the first element within the document (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors.
More on querySelector
: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
seems like it is working correctly. Maybe you should move your script below the HTML. or check for document ready.
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>
You need to remove the var cls=...
. Here's a working jsFiddle.
As per your updated requirement(Expected is "Change Text" should replace "Your submission was successful."
)
You cannot update the inner html of animate-in
as it will remove the button element also.
So one solution will be is to update only the first child of animate-in
which is the text node containing the value like
document.querySelector("#global-alert-queue .animate-in").firstChild.nodeValue = "Change Text";
Another way is to update the markup to wrap the text in another element like
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>
you can add button as string with Text then you get your Output 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>