是否有一种简单的方法只使用vanilla javascript更改元素的文本?在下面的代码中,我认为使用.textContent
而不是.innerHTML
会更改文本并将图像留在后面。
<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>
我也曾尝试过,但很多都没有成功:
function change_stuff() {
var div = document.getElementById('to_change');
var text = div.textContent;
div.textContent = text.replace(text, "");
}
任何帮助将不胜感激
答案 0 :(得分:7)
获取firstChild
属性的第一个textNode并更新内容。
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>
答案 1 :(得分:2)
在 W3C DOM (Document Object Model) 中, 所有 都是&#34;节点&#34;。节点有 different types (注释节点,元素节点,属性节点甚至文本节点)。像div
这样的元素没有任何嵌套元素可以在其中包含文本实际上隐含地在其中包含原始文本且该元素是一个子元素,这似乎是违反直觉的。文本节点。
为了访问它(它将与div
中的其他元素分开,您可以导航到div
并查找(在这种情况下,它 firstChild
,因为文字首先出现,图片排在第二位。
此外,在用其他内容替换原始文本时...您试图在.replace()
上调用div
字符串函数而不是div
中的文本。您可以通过导航到其中的文本节点并仅使用该文本节点来仅隔离div
的文本。
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, "");
}
&#13;
<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>
&#13;
答案 2 :(得分:1)
您需要使用 innerText 在div中设置文本(即:div.innerText = replacement
)。
答案 3 :(得分:0)
还是务实的:
function change_stuff() {
var div = document.getElementById('to_change'),
img = div.getElementsByTagName('img')[0];
div.innerHTML = "OMG...it's an image!";
div.appendChild(img);
}
&#13;
<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>
&#13;