• 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     }
  • 相关阅读:
    JAVA应用apache httpclient探测http服务
    C#中字符串与byte[]相互转换
    C#中位、字节等知识
    #JAVA操作LDAP
    C#正则表达式判断字符串是否是金钱
    【IDEA】使用Maven骨架创建JavaWeb项目
    【IDEA】回退操作记录
    【SpringMVC】IDEA 不识别webapp的解决办法
    【Layui】16 表单元素 Form
    【Layui】15 日期时间选择器 Laydate
  • 原文地址:https://www.cnblogs.com/alala666888/p/3293127.html
Copyright © 2020-2023  润新知