javascript遍历子元素

    最近写代码时需要获取符合某些条件的节点子元素,用firstChild之类的方法会包含文本节点,所以包装了一个简单的类:

 1     //子元素遍历器
 2     function ElementWalker(node) {
 3         if(typeof node === 'string')
 4             node = document.getElementById(node);
 5         this.node = node;
 6     }
 7     ElementWalker.prototype = {
 8         //获取第一个指定tagName的子元素,如果tagName没定义,则返回第一个子元素
 9         first: function(tagName) {
10             if((typeof tagName === 'undefined') && this.node.firstElementChild) {
11                 return new ElementWalker(this.node.firstElementChild);
12             }
13             for(i = 0; i < this.node.childNodes.length; i++) {
14                 if(this.checkChild(i,tagName)) {
15                     return new ElementWalker(child);
16                 }
17             }
18         },
19         //获取最后一个指定tagName的子元素,如果tagName没定义,则返回最后一个子元素
20         last: function(tagName) {
21             if((typeof tagName === 'undefined') && this.node.lastElementChild) {
22                 return new ElementWalker(this.node.lastElementChild);
23             }
24             for(i = parent.childNodes.length - 1; i >= 0; i--) {
25                 var child = this.node.childNodes[i];
26                 if(this.checkChild(child,tagName)) {
27                     return new ElementWalker(child);
28                 }
29             }            
30         },
31         //返回所有指定tagName的子元素,如果tagName没定义,则返回所有子元素
32         all: function(tagName) {
33             var children = [];
34             for(i = 0; i < this.node.childNodes.length; i++) {
35                 var child = this.node.childNodes[i];
36                 if(this.checkChild(child,tagName)) {
37                     children.push(new ElementWalker(child));
38                 }
39             }
40             return children;
41         },
42         //校验child是否是指定tagName的元素
43         checkChild : function(child,tagName) {
44             var isOK = (typeof tagName === 'undefined') && child.nodeType == 1;
45             isOK = isOK || (child.tagName && child.tagName.toLowerCase() === tagName);
46             return isOK;
47         }
48     }

 

转载于:https://www.cnblogs.com/alala666888/p/3293127.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值