不使用JQuery选择HTML Element

来源:互联网 发布:宋徽宗 知乎 编辑:程序博客网 时间:2024/06/04 19:18
  • ID document.getElementById('myElement'); 或者document.querySelector('#myElement');
  • Class document.getElementsByClassName('myElement');或者document.querySelectorAll('.myElement');
  • HTML标签document.getElementsByTagName('div');或者`.querySelectorAll(‘div’);`
  • 属性 document.querySelectorAll('[attr-name="val"]');
  • Pseudo-class document.querySelectorAll('#elmem :invalid');
  • 子元素document.getElementById('holder').childNodes;document.getElementById('holder').children;或者document.querySelector('#holder > [disabled]');
  • 后代元素`document.querySelectorAll(‘#holder A’);
  • 排除 `document.querySelectorAll(‘DIV:not(.exclude)’);
  • document.querySelectorAll('h1, h2, p');

    window.picker = function(selector) {var selectorType = 'querySelectorAll';if (selector.indexOf('#') === 0) {    selectorType = 'getElementById';    selector = selector.substr(1, selector.length);}return document[selectorType](selector);};

Mozilla 文档
You Don’t Need Jquery