Use javascript to change text only in an element
Get the first textNode by firstChild
property and update the content.
function change_stuff() {
// get the first child node, in your code which is the text node
var t = document.getElementById('to_change').firstChild;
// update the text contents in the node
t.nodeValue = "";
// or t.textContent = "";
// or remove the node itself
// t.parentNode.removeChild(t)
}
<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>
You need to use innerText to set the text within the div (i.e.: div.innerText = replacement
).
See Node.textContent - Differences from innerText.
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 the div
and look for (in this case, it's firstChild
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 the div
and not the text within the div
. You can isolate just the text of the div
by navigating to the text node within it and working just on that.
function change_stuff() {
// Get a reference to the div element's text node which is a child node
// of the div.
var divText = document.getElementById('to_change').firstChild;
// Get the current text within the element:
var text = divText.textContent;
// You can do whatever you want with the text (in this case replace)
// but you must assign the result back to the element
divText.textContent = text.replace(text, "");
}
<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>
Or the pragmatic:
function change_stuff() {
var div = document.getElementById('to_change'),
img = div.getElementsByTagName('img')[0];
div.innerHTML = "OMG...it's an image!";
div.appendChild(img);
}
<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 type="button" onclick="change_stuff();">
ThE dOER!!
</button>