Selecting Elements 选择元素

By ID

jQuery

// returns a jQuery obj w/ 0-1 elements
$('#myElement');

DOM API

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

...or...

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

By CSS Class

jQuery

// returns a jQuery obj w/ all matching elements
$('.myElement');

DOM API

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

...or...

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

By Tag Name

For example, to select all

elements on a page:

jQuery

$('div');

DOM API

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

...or...

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

By Attribute

Select all elements with a "data-foo-bar" attribute that contains a value of "someval":

jQuery

$('[data-foo-bar="someval"]');

DOM API

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

By Pseudo-class

Select all fields in a specific form that are currently invalid. Let's assume our form has an ID of "myForm".

jQuery

$('#myForm :invalid');

DOM API

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

Children

Select all children of a specific element. Let's assume our specific has an ID of "myParent".

jQuery

$('#myParent').children();

DOM API

// IE 5.5+
// NOTE: This will include comment and text nodes as well.
document.getElementById('myParent').childNodes;

...or...

// IE 9+ (ignores comment & text nodes).
document.getElementById('myParent').children;

But what if we want to only find specific children? Say, only children with an attribute of "ng-click"?

jQuery

$('#myParent').children('[ng-click]');

...or...

$('#myParent > [ng-click]');

DOM API

// IE 8+
document.querySelector('#myParent > [ng-click]');

Descendants

Find all anchor elements under #myParent.

jQuery

$('#myParent A');

DOM API

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

Excluding Elements 反选元素

Select all <div> elements, except those with a CSS class of "ignore".

jQuery

$('DIV').not('.ignore');

...or...

$('DIV:not(.ignore)');

DOM API

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

Multiple Selectors

Select all

, and

results matching ""

    No results matching ""