【问题标题】:Remove plain HTML text withing a div删除 div 中的纯 HTML 文本
【发布时间】:2022-01-30 08:44:41
【问题描述】:

如何在不删除其他文本的情况下删除 HTML 中的“当前”

<div class="group if-description-margin">
  Currently:  <--- Remove this text
  <a href="/media/images/header-dots.png">images/header-dots.png</a>
  <input type="checkbox" name="profile_picture-clear" id="profile_picture-clear_id">
 
  <input type="file" name="profile_picture" accept="image/*" id="id_profile_picture">
  <p> But don't remove this </p>
  <label for="id_profile_picture">Profile Picture</label>
</div>

【问题讨论】:

  • 在python中你可以使用html_text.replace("Currently", "')

标签: javascript python html css django


【解决方案1】:

您可以使用regexpinnerHTML

const textContainer = document.querySelector('.group')
const btn = document.getElementById('remove')

const removeText = (el, regexp) => {
  const oldHTML = el.innerHTML
  const newHTML = oldHTML.replace(regexp, '')
  return newHTML
}

const regexp = /Currently:/g

btn.addEventListener('click', function() {
  textContainer.innerHTML = removeText(textContainer, regexp)

})
<div class="group if-description-margin">
  Currently: <!-- Remove this text -->
  <a href="/media/images/header-dots.png">images/header-dots.png</a>
  <input type="checkbox" name="profile_picture-clear" id="profile_picture-clear_id">

  <input type="file" name="profile_picture" accept="image/*" id="id_profile_picture">
  <p> But don't remove this </p>
  <label for="id_profile_picture">Profile Picture</label>
</div>
<button id="remove">REMOVE THE TEXT</button>

【讨论】:

    【解决方案2】:

    您可以充分利用 DOM。如果您有对父 Div 的引用,则可以使用它的 childNodes 属性 (https://www.w3schools.com/jsref/prop_node_childNodes.asp)。它只返回 HTML 元素,而不是文本节点。您可以编写一个非常简单的函数,循环通过 childNodes 来重建 innerHTML,并且通过愉快的副作用,它会遗漏文本节点。

    如果您想删除特定的文本节点,您可以使用包含文本节点和 html 元素的 children 属性 (https://www.w3schools.com/jsref/prop_element_children.asp)。然后你仍然循环遍历子元素并添加逻辑来决定是否将其添加回 innerHTML。

    编辑:添加到我的测试页面的链接... https://highdex.net/StackOverflow/DOMHelper.htm

    编辑 2: 进一步解释 我最终只使用了 childNodes 集合。而不是清除和重建,我只是删除了文本节点(或符合条件的文本节点)。第二个函数的变量分配比必要的要多,但我在调试期间将其分解,以便更容易看到正在使用的值。它应该被清理干净,但不会影响你对它的理解。最后要提到的一件事是,在 for 循环中递减计数器必须以这种方式完成。如果您首先尝试从头开始删除内容,它会避免尝试访问可能不再存在的索引。

    【讨论】:

      猜你喜欢
      • 2012-11-18
      • 2018-04-03
      • 2016-04-22
      • 2017-03-31
      • 2011-07-10
      • 2010-10-16
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      相关资源
      最近更新 更多