如何遍历一些特定的子节点 [英] how to loop through some specific child nodes

查看:109
本文介绍了如何遍历一些特定的子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个DOM树:

I have this DOM tree:

<li> 
data ....
  <br>
  data ...
  <img ... />
  <br>
  <script> ... </script>
  <span> data ... </span>
</li>

如何循环li元素和脚本元素之间的上述li元素的子元素,即脚本和span元素不在循环中...
感谢advace !!

how can I loop through the children of the above li element that fall between the li itself and script element, i.e. script and span elements are out of the loop ... thanks in advace !!

注意:我不想使用JQuery,因为我的app正在使用Protoype,如果我将它们两个同时使用,它会与JQuery发生冲突,如果使用Prototype有一个快速解决方案,我会很感激。

note: I do not want to use JQuery, because my app is using Protoype and it will conflict with JQuery if I use both of them together, i'd appreciate it if there's a quick solution using Prototype.

推荐答案

会这样的工作吗?

var child = liElement.firstChild;
while(child){
    if(child.nodeName.toLowerCase() == 'script'){
        break
    }
    //do your stuff here
    child = child.nextSibling;
}

请注意,如果您的示例中的数据是字符串,作为textNodes的实例存在于儿童阶层中。如果你需要对这些东西进行特殊处理,你会想做一些检查,比如

Note, the if the "data" in your example are strings, these will exist in the child heirarchy as instances of textNodes. if you need to do special processing on this stuff, you will want to do a check such as

switch(child.nodeType){
case 3:
   //text Node
   break;
case 1:
   //Element node
   break;
default:
    //break;
}

查看
https://developer.mozilla.org/en/nodeType 获取更多节点类型。

check out https://developer.mozilla.org/en/nodeType for more node types

这篇关于如何遍历一些特定的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆