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

发布于 2024-11-17 05:11:42 字数 1185 浏览 3 评论 0原文

我有一些从 php 脚本动态生成的 html。 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";

我有一个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'];
..
...
..

现在这不能按预期工作,因为html中有文本节点。 当我使用 firebug 控制台 尝试此操作时,

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

它显示 3 这意味着该节点是一个文本节点。 我尝试像这样在 window.onload 中添加 document.normalize();

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

但文本节点仍保留在 html 中。我怎样才能删除所有文本节点。现在我认为没有像 getElementByType() 这样的方法,那么我如何获取所有文本节点。

i have some dynamically generated html from a php script. the php code looks like this

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

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.
when i used the firebug console to try this

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

it displays 3 which means that the node is a text node.
i tried adding document.normalize(); in window.onload like this

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

but the text nodes remain in the 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我要还你自由 2024-11-24 05:11:42

使用 .children 而不是 .childNodes 仅定位元素(无文本节点):

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

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 );

另请注意,IE 也会为您提供注释节点,因此如果您的标记不包含注释会更好。

Use .children instead of .childNodes to target elements only (no text nodes):

   // --------------------------------------------------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.

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.

迷鸟归林 2024-11-24 05:11:42

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>

细分:

  1. 获取所有子项
  2. 将 HTMLCollection 转换为数组
  3. 遍历数组并检查每个项目是否为 文本节点类型
  4. 如果是,则从 DOM 中删除该项目

这只会删除直接子文本节点,而不会删除树中更深层的内容。


with 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>

EE2015 syntax:

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
  3. Traversing the Array and checking each item if it's of type text node
  4. If so, remove the item from the DOM

This will only remove direct-child text nodes and nothing deeper in the tree.


with 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>

陪你搞怪i 2024-11-24 05:11:42

为什么不使用 getElementsByClassName MDC 文档

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

对于本身不支持它的浏览器,请查看以下实现:http://ejohn.org/blog /getelementsbyclassname-speed-comparison/

Why don't you use getElementsByClassName MDC docs instead ?

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

For browsers that do not natively support it look at these implementations : http://ejohn.org/blog/getelementsbyclassname-speed-comparison/

亽野灬性zι浪 2024-11-24 05:11:42

检查循环中的每个节点,如果它是文本节点,则按照您所说的删除它或不执行任何操作。如果它不是文本节点,请对其执行您想要执行的操作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文