Read more

Use jQuery's selector engine on vanilla DOM nodes

Henning Koch
December 28, 2015Software engineer at makandra GmbH

There are cases when you need to select DOM elements without jQuery, such as:

  • when jQuery is not available
  • when your code is is extremely performance-sensitive
  • when you want to operate on an entire HTML document (which is hard to represent as a jQuery collection).
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

To select descendants of a vanilla DOM element (i.e. not a jQuery collection), one option is to use your browser's native querySelector Show archive.org snapshot and querySelectorAll Show archive.org snapshot functions.

var container = document.body.querySelector('.container');
var openTasks = container.querySelectorall('.task.open');

While these functions are supported on all modern browsers Show archive.org snapshot , they won't understand jQuery's non-standard but awesome selectors Show archive.org snapshot such as :has Show archive.org snapshot or :visible Show archive.org snapshot .

What you can do instead is to use Sizzle Show archive.org snapshot , the selector engine that is embedded into jQuery. jQuery.find (or $.find) is an alias for the Sizzle(...) function Show archive.org snapshot , which you can use to select descendants from a vanilla DOM node:

var container = $.find('.container', document.body)[0];
var openTasks = $.find('.task.open', container);

Note that Sizzle returns vanilla DOM nodes in a vanilla Javascript array. It does not return jQuery collections.

Posted by Henning Koch to makandra dev (2015-12-28 11:49)