【问题标题】:How to remove the specific text node from the DOM如何从 DOM 中删除特定的文本节点
【发布时间】:2014-06-10 01:38:42
【问题描述】:

我正在尝试删除文本节点“one”。

$targetDiv 是 jQuery 对象

$targetDiv[0].outerHTML
<div><div>one<font face="Impact" size="4">www</font></div></div>

$targetDiv[0].innerHTML
<div>one<font face="Impact" size="4">www</font></div>

我可以删除其他文本节点“www”,如下所示:

$targetDiv.find("font").each(function ()
{
   if (this.firstChild.nodeType === 3)
   {
       this.firstChild.data = "";
   }
}); 

但是很难去除“一个”部分。

$targetDiv[0].firstChild
<div>

$targetDiv[0].firstChild.data
undefined

$targetDiv[0].firstChild.innerText
undefined

$targetDiv[0].firstChild.innerHTML
"one<font face="Impact" size="4">www</font>"

$targetDiv[0].firstChild.innerText
undefined

$targetDiv[0].firstChild.textContent
"onewww"

【问题讨论】:

    标签: javascript jquery html firefox dom


    【解决方案1】:

    你可以使用原生的.removeChild方法来移除第一个文本节点:

    var div=targetDiv[0].firstChild;
    div.removeChild(div.firstChild);
    

    此方法从您要删除的节点的父节点调用,并接收要删除的节点作为其参数。


    现代浏览器让您只需在节点本身上调用.remove()

    target[0].firstChild.firstChild.remove();
    

    您的.each() 循环已关闭。在这种特殊情况下,由于 one 文本节点是唯一的文本节点兄弟,因此您只需迭代目标下的子节点,因为只有一个。

    $targetDiv.children("div").each(function ()
    {
       if (this.firstChild.nodeType === 3)
       {
           this.firstChild.data = "";
       }
    });
    

    虽然在这种情况下直接定位它而不是循环更有意义。

    【讨论】:

      【解决方案2】:

      目前还不清楚这是在什么上下文中,或者$targetDiv 是什么,但根据你得到的结果,我们可以假设你使用的是 Firefox,$targetDiv 是第一个 div,并且这个应该工作

      $($targetDiv.find("div").get(0).firstChild).remove();
      

      FIDDLE

      【讨论】:

        【解决方案3】:

        试试,

        $($targetDiv.children('div').contents()[0]).remove();
        

        DEMO

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-26
          • 2023-03-27
          • 1970-01-01
          • 1970-01-01
          • 2019-10-29
          • 1970-01-01
          相关资源
          最近更新 更多