SCENARIO
I have the following HTML code snippet:
<div class="container">
TEXT
<p> PARAGRAPH 1 </p>
<p> PARAGRAPH 2 </p>
<p> PARAGRAPH 3 </p>
<p> PARAGRAPH 4 </p>
</div>
I am required to change the plain text using JS/jQuery, using the HTML DOM methods.
PROBLEM
** I can access the "plain text" node using
document.getElementsByClassName("container")[0].childNodes[0]
** However, I can't use the innerHTML
, as it returns "undefined
":
document.getElementsByClassName("container")[0].childNodes[0].innerHTML
** Using the replaceChild
method doesn't work either (it triggers an Uncaught DOMException
at the console log).
var textnode = document.createTextNode("THE TEXT HAS BEEN REPLACED");
var element = document.getElementsByClassName("container")[0].childNodes[0];
item.replaceChild(textnode, item);
** And finally, using
document.getElementsByClassName("container")[0].innerHTML
selects all the HTML content inside <div class="container">
.
Is there any way I can access the text content of "TEXT" and change it dynamically?
JSFIDDLE