简体   繁体   English

删除所有子节点,但将节点的文本内容保留在javascript中(无框架)

[英]Remove all child nodes but leave the text content of the node in javascript (no framework)

I'm trying to remove all child elements from a node but leave the actual text content of the node. 我正在尝试从节点中删除所有子元素,但保留该节点的实际文本内容。 Ie go from this: 即从此:

<h3>
   MY TEXT
   <a href='...'>Link</a>
   <a href='...'>Link</a>
   <select>
      <option>Value</option>
      <option>Value</option>
   </select>
</h3>

to this: 对此:

<h3>
   MY TEXT
</h3>

I know that there are a million easy ways to do this in jQuery , but it's not an option for this project... I've got to use plain old javascript . 我知道在jQuery中有一百万种简单的方法可以做到这一点 ,但这不是该项目的选择...我必须使用普通的旧javascript

This: 这个:

var obj = document.getElementById("myID");
if ( obj.hasChildNodes() ){
    while ( obj.childNodes){
        obj.removeChild( obj.firstChild );       
    }
}

obviously results in just <h3></h3> , and when I tried: 显然只产生<h3></h3> ,当我尝试时:

var h3 = content_block.getElementsByTagName('h3')[0];
var h3_children = h3.getElementsByTagName('*');
for(var i=0;i<h3_children.length;i++){
   h3_children[i].parentNode.removeChild(h3_children[i]);
}

It gets hung up part way through. 它被挂断了一部分。 I figured it was having trouble removing the options, but altering the for loop to skip removal unless h3_children[i].parentNode==h3 (ie only remove first-level child-elements) stops after removing the first <a> element. 我发现它在删除选项时遇到麻烦,但是除非删除第一个<a>元素后h3_children[i].parentNode==h3 (即仅删除第一级子元素)停止,否则更改for循环以跳过删除。

I'm sure I'm missing something super obvious here, but perhaps it's time to turn to the crowd. 我确定我在这里错过了一些非常明显的东西,但是也许是时候转向人群了。 How can I remove all child elements but leave the first-level textNodes alone? 如何删除所有子元素,但不保留第一级textNodes And why doesn't the above approach work? 为什么上述方法不起作用?

EDITS EDITS

There are a couple of working solutions posted, which is great, but I'm still a little mystified as to why looping through and removing h3.getElementsByTagName('*') doesn't work. 发布了两个h3.getElementsByTagName('*')解决方案,这很棒,但是对于为什么循环遍历和删除h3.getElementsByTagName('*')无效,我还是有些迷惑。 A similar approach (adapted from Blender ) likewise does not complete the process of removing child nodes. 同样的方法 (从Blender改编而成)同样无法完成删除子节点的过程。 Any thoughts as to why this would be? 有什么关于为什么会这样的想法?

var h3=content_block.getElementsByTagName("h3")[0];
for(var i=0;i<h3.childNodes.length;i++)
{
  if(h3.childNodes[i].nodeType==3)//TEXT_NODE
  {
    continue;
  }
  else
  {
    h3.removeChild(h3.childNodes[i]);
    i--;
  }
}

JSFiddle demo JSFiddle演示

Edit : 编辑

Combined the i-- to make it look shorter: 组合i--使它看起来更短:

var h3=content_block.getElementsByTagName("h3")[0];
for(var i=0;i<h3.childNodes.length;i++)
{
  if(h3.childNodes[i].nodeType==3)//TEXT_NODE
    continue;
  else
    h3.removeChild(h3.childNodes[i--]);
}

Edit #2: 编辑 #2:

Pointed out by @SomeGuy, make it even shorter: 由@SomeGuy指出,使其更短:

var h3=content_block.getElementsByTagName("h3")[0];
for(var i=0;i<h3.childNodes.length;i++)
{
  if(h3.childNodes[i].nodeType!=3)//not TEXT_NODE
    h3.removeChild(h3.childNodes[i--]);
}

The brackets can be removed too, but that would be "less readable" and "confusing", so I keep it there. 括号也可以删除,但是那“可读性较差”和“令人困惑”,因此我将其保留在那里。

You can check properties .nodeType or .nodeName for each node. 您可以检查每个节点的属性.nodeType.nodeName

Text nodes have these properties set to: 文本节点的这些属性设置为:

.nodeType == 3
.nodeName == '#text'`

For instance: 例如:

var e = obj.firstChild
while (e) {
   if (e.nodeType == 3) {
      e = e.nextSibling
   } else {
      var n = e.nextSibling
      obj.removeChild(e)
      e = n
   }
}

try this. 尝试这个。 I am assuming you will keep ant text here. 我假设您将在此处保留蚂蚁文字。

var h3 = document.getElementsByTagName('h3')[0];

if (h3.hasChildNodes()) {
    for (var i = h3.childNodes.length - 1; i >= 0; i--) {
        if (h3.childNodes[i].nodeName != "#text")
            h3.removeChild(h3.childNodes[i]);
    }
}

Hope it will work. 希望它能工作。

Well, The thing I used (inspired from the answers here) is somewhat like: 好吧,我使用的东西(从这里的答案中得到启发)有点像:

   var h3 = document.getElementsByTagName("h3")[0];
    Array.protoype.filter.call(h3.childNodes, function(child){
        if (child.nodeType != 3) {
            h3.removeChild(child);
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM