zoukankan      html  css  js  c++  java
  • getElementsByClass

    The DOM provides a number of powerful methods for accessing nodes in a document. But there are also some surprising omissions.

    For instance, although we have an insertBefore method, there is no corresponding insertAfter. Still, it’s possible to recombine existing DOM methods to plug the gaps in the DOM specs.

    One of the most useful DOM methods of all is getElementById. It would be equally useful to have a getElementsByClass method.

    Many, many coders have stepped up to bat on this issue by recombining getElementsByTagName("*") and className. The tricky bit is matching the value of className with the class you’re looking for. Remember that classes can be combined by separating them with spaces.

    I came across a nice getElementsByClass function from Dustin Diaz:

    function getElementsByClass(node,searchClass,tag) {
      var classElements = new Array();
      var els = node.getElementsByTagName(tag);
      var elsLen = els.length;
      var pattern = new RegExp("\b"+searchClass+"\b");
      for (i = 0, j = 0; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
          classElements[j] = els[i];
          j++;
        }
      }
    return classElements;
    }
    

    It uses a regular expression to match the className which is perhaps a bit more resource-intensive than just using something like indexOf but it decreases the chances of getting false positives.

    The function takes three arguments: node, searchClass and tag.

    The node can simply be document if you want to search the whole document or you can pass it a result from getElementById (for example).

    The searchClass parameter is the name of the class you want to match.

    The tag parameter allows you to restrict the search to a specific tag. You can simply use the wildcard (“*”) to search all tags.

    All in all, a nice little function.

    link:http://domscripting.com/blog/display/18

  • 相关阅读:
    linux 重定向命令
    G++依赖安装顺序
    SQL*Plus Error Messages
    理解 chroot
    CRM的基本功能有哪些?
    GCC依赖安装顺序
    RHEL6.3 安装GCC 记录
    python requests模块http请求
    安装paramiko模块
    python执行系统命令的方法:os.system(), os.popen(), subprocess.Popen()
  • 原文地址:https://www.cnblogs.com/sirkevin/p/2157359.html
Copyright © 2011-2022 走看看