7 html javascript text replace
是否有一种简单的方法只使用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>
Run Code Online (Sandbox Code Playgroud)
我也尝试过,但很多都没有成功,有很多变化:
function change_stuff() {
var div = document.getElementById('to_change');
var text = div.textContent;
div.textContent = text.replace(text, "");
}
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激
Pra*_*lan 10
按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)
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
在W3C DOM(文档对象模型)中,一切都是“节点”。节点有不同的类型(注释节点、元素节点、属性节点甚至文本节点)。像这样的元素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, "");
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)