no-jquery 01Elements

时间:2023-03-09 23:23:14
no-jquery 01Elements

Select Elements

id

// IE 5.5+
document.getElementById('myElement'); // IE 8+
document.querySelector('#myElement');

class

// IE 9+
document.getElementsByClassName('myElement'); // IE 8+
document.querySelectorAll('.myElement');

Pseudo-class

// IE 8+
document.querySelectorAll('#myForm :invalid');

tagName

// IE 5.5+
document.getElementsByTagName('div'); // IE 8+
document.querySelectorAll('div');

attribute

// IE 8+
document.querySelectorAll('[data-foo-bar="someval"]');

Children

// IE 5.5+
// NOTE: This will include comment and text nodes as well.
document.getElementById('myParent').childNodes; // IE 9+ (ignores comment & text nodes).
document.getElementById('myParent').children; // IE 8+
document.querySelector('#myParent > [ng-click]');

Descendants

// IE 8+
document.querySelectorAll('#myParent A');

Excluding Elements

// IE 9+
document.querySelectorAll('DIV:not(.ignore)');

Multiple Selectors

// IE 8+
document.querySelectorAll('DIV, A, SCRIPT');

Pattern

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