使用JavaScript更改仅元素中的文本 [英] Use javascript to change text only in an element
本文介绍了使用JavaScript更改仅元素中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种简单的方法可以仅使用普通javascript来更改元素的文本?在下面的代码中,我认为使用.textContent
而不是.innerHTML
会更改文本并将图像保留在后面.
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, "");
}
任何帮助将不胜感激
推荐答案
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>
这篇关于使用JavaScript更改仅元素中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文