javascript - 使用javascript仅更改元素中的文本

标签 javascript html 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>

我也尝试过但几乎没有成功:

function change_stuff() {
    var div = document.getElementById('to_change');
    var text = div.textContent;

    div.textContent = text.replace(text, "");
}

任何帮助将不胜感激

最佳答案

通过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>

关于javascript - 使用javascript仅更改元素中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41384379/

相关文章:

javascript - 工具提示样式? (朝正确的方向踢我)

html - 可变高度容器内元素的垂直中间

android - 将 x/y 坐标转换为文本

javascript - 无法使用查询从 Sqlite 数据库获取值

javascript - 删除右键单击表格箭头 firefox

Javascript,设置允许的字符函数

javascript - 如何使用 vanilla Javascript 将一个输入字段的值附加到另一个输入字段的值中?

file - 根据文件是否包含字符串进行搜索然后删除

python - 如何使用 python-pptx 从 powerpoint 中的组形状中的文本形状中提取文本。

javascript - AngularJS - 为什么 ng-mouseleave 不能正常工作?