Is there a simple way to change the text of an element only using vanilla javascript? In the code below, I thought that using .textContent
, rather than .innerHTML
would change the text and leave the image behind.
<head>
<script>
function change_stuff() {
var div = document.getElementById('to_change');
div.textContent = "OMG...it's an image!";
}
</script>
</head>
<body>
<div id="to_change">
This is a huge block of text that I want to replace while leaving the image in place
<img src="./the_image.jpg">
</div>
<button onclick="change_stuff();">
ThE dOER!!
</button>
</body>
I've also tried but had little to no success with many variations of this:
function change_stuff() {
var div = document.getElementById('to_change');
var text = div.textContent;
div.textContent = text.replace(text, "");
}
Any help would be appreciated
In the W3C DOM (Document Object Model), everything is a "node". Nodes come in different types (comment nodes, element nodes, attribute nodes and even text nodes). It may seem counter-intuitive that an element like
div
that doesn't have any nested elements that can contain text inside it actually does implicitly have a child element within it that contains the raw text and that element is a text node.In order to access that (which will be separate from other elements within the
div
, you can navigate to thediv
and look for (in this case, it'sfirstChild
because the text comes first and the image is second.Also, when it comes to replacing the original text with something else...You were trying to call the
.replace()
string function on thediv
and not the text within thediv
. You can isolate just the text of thediv
by navigating to the text node within it and working just on that.Or the pragmatic:
Get the first textNode by
firstChild
property and update the content.