简体   繁体   English

使用javascript从特定div标签中删除所有文本节点

[英]removing all text nodes from a particular div tag using javascript

i have some dynamically generated html from a php script.我有一些从 php 脚本动态生成的 html。 the php code looks like this php 代码看起来像这样

echo "<div id='categories'>\n";
foreach($category as $k => $v)
{
echo "<div class='category'>\n";
echo "<div id=\"$k\" class='cat_name'\n>$k</div>\n";
echo "<div id=\"$k".'_link"'." class='cat_link'>\n<a href=$v>Link</a>\n</div>\n";
echo "</div>\n";
}
echo "</div>\n";

i have a javascript file that tries to access the dom like this我有一个 javascript 文件试图像这样访问 dom

var categories=document.getElementById('categories').childNodes;
for(i=0;i<categories.length;i++)
{
var link=categories[i].childNodes[1].childNodes[0].attributes['href'];
..
...
..

now this doesnt work as expected because there are text nodes in the html.现在这不能按预期工作,因为 html 中有文本节点。 when i used the firebug console to try this当我使用firebug console尝试此操作时

document.getElementById('categories').childNodes[0].nodeType; // displays 3 

it displays 3 which means that the node is a text node .它显示3这意味着该节点是一个text node i tried adding document.normalize();我尝试添加document.normalize(); in window.onload like thiswindow.onload像这样

window.onload=function() {
document.normalize();
var categories=document.getElementById('categories').childNodes;
...
...

but the text nodes remain in the html.但文本节点保留在 html 中。 how can i remove all the text nodes.如何删除所有文本节点。 now i dont think there is any method like getElementByType() so how do i get all text nodes.现在我认为没有像getElementByType()这样的方法,所以我如何获取所有文本节点。

EE2015 syntax: EE2015 语法:

 var elm = document.querySelector('ul'); console.log(elm.outerHTML); // remove all text nodes [...this.elm.childNodes].forEach(elm => elm.nodeType != 1 && elm.parentNode.removeChild(elm)) console.log(elm.outerHTML);
 <ul> <li>1</li> a <li>2</li> b <li>3</li> </ul>

Breakdown:分解:

  1. Get all children得到所有孩子
  2. Convert the HTMLCollection to an Array将 HTMLCollection 转换为数组
  3. Traversing the Array and checking each item if it's of type text node遍历数组并检查每个项目是否为文本节点类型
  4. If so, remove the item from the DOM如果是,则从 DOM 中删除该项目

This will only remove direct-child text nodes and nothing deeper in the tree.这只会删除直接子文本节点,而不会删除树中更深的内容。


with NodeIterator :使用NodeIterator

 var elm = document.querySelector('ul') // print HTML BEFORE removing text nodes console.log(elm.outerHTML) // remove all text nodes var iter = document.createNodeIterator(elm, NodeFilter.SHOW_TEXT) var node; while (node = iter.nextNode()) { node.parentNode.removeChild(node) } // print HTML AFTER removing text nodes console.log(elm.outerHTML)
 <ul> <li>1</li> <li>2</li> <li>3<span>4</span></li> </ul>

Use .children instead of .childNodes to target elements only (no text nodes):仅使用.children而不是.childNodes来定位元素(无文本节点):

   // --------------------------------------------------v
var categories=document.getElementById('categories').children;

FF3 doesn't support that property, so if you're supporting that browser, you'll need a method to replicate it. FF3 不支持该属性,因此如果您支持该浏览器,则需要一种方法来复制它。

function children( parent ) {
    var node = parent.firstChild;
    var result = [];
    if( node ) {
        do {
            if( node.nodeType === 1 ) {
                result.push( node );
            }
        } while( node = node.nextSibling )
    }
    return result;
}
var parent = document.getElementById('categories');
var categories= parent.children || children( parent );

Also note that IE will give you comment nodes as well, so it would be better if your markup didn't include comments.另请注意,IE 也会为您提供注释节点,因此如果您的标记不包含注释会更好。

Why don't you use getElementsByClassName MDC docs instead ?为什么不使用getElementsByClassName MDC 文档呢?

var categories=document.getElementByClassName('category');

For browsers that do not natively support it look at these implementations : http://ejohn.org/blog/getelementsbyclassname-speed-comparison/对于本身不支持它的浏览器,请查看这些实现: http : //ejohn.org/blog/getelementsbyclassname-speed-comparison/

Check each node in your loop and if it's a text node, then either remove it as you said or do nothing.检查循环中的每个节点,如果它是文本节点,则按照您所说的将其删除或不执行任何操作。 If it's not a text node, do what action you want to do to it.如果它不是文本节点,请执行您想要对其执行的操作。

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

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