Modify prototypes of every possible DOM element

后端 未结 2 2067
故里飘歌
故里飘歌 2020-12-11 21:59

Updated title to better reflect what I\'m trying to do.

In short, there are different constructors for different dom elements, and they don\'t seem to all share a co

2条回答
  •  抹茶落季
    2020-12-11 22:05

    This seems to work, but it's ugly. I wonder if it works in IE?

    (function(){
    
      enhanceDom('a abbr acronym address applet area b base basefont bdo big blockquote body br button caption center cite code col colgroup dd del dfn dir div dl dt em fieldset font form frame frameset h1 h2 h3 h4 h5 h6 head hr html i iframe img input ins isindex kbd label legend li link map menu meta noframes noscript object ol optgroup option p param pre q s samp script select small span strike strong style sub sup table tbody td textarea tfoot th thead title tr tt u ul var'
      ,{
        getElementsByClassName : getByClass
        /* , ... */
      });
    
      function enhanceDom (tagNames, methods) {
        var i=-1, tagName;
        if (tagNames==''+tagNames) {
          tagNames=tagNames.split(' ');
        }
        for (var methodName in methods) {
          setIfMissing(document, methodName, methods[methodName]);
          while (tagName=tagNames[++i]) {
            var tag=document.createElement(tagName);
            if (tag || !tag.constructor) continue;
            var proto=tag.constructor.prototype;
            setIfMissing(proto, methodName, methods[methodName]);
          }
        }
      }
    
      function setIfMissing (obj, prop, val) {
        if (typeof obj[prop] == 'undefined') {
          obj[prop]=val;
        }
      }
    
      function withDescendants (node, callback, userdata) {
        var nodes=node.getElementsByTagName('*'), i=-1;
        while (node=nodes[++i]) {
          callback(node, userdata);
        }
        return userdata;
      }
    
      function getByClass (className) {
        return withDescendants(this, getMatches, {
          query:new RegExp('(^|\\s+)' + className + '($|\\s+)'), 
          found:[]
        }).found;
      }
    
      function getMatches (node, data) {
        if (node.className && node.className.match(data.query)) {
          data.found.push(node);
        }
      }
    
    }());
    

提交回复
热议问题