Writing jQuery find() in Pure Javascript

To do the conversion of $.find() to pure Javascript, you need to know 2 native Javascript methods :

  • document.querySelectorAll : This method returns all elements in the document that matches a specified CSS selector as an array-like collection of DOM elements (NodeList).
  • document.querySelector : This method returns returns only the first element that matches a specified CSS selector. It works in the same way, the difference being :
    document.querySelector() returns a single element.
    document.querySelectorAll() returns an "array-like" collection of elements.

I'll demonstrate the conversion of find() to Javascript using simple examples.

Simple Case - When Outer Selector is a Single Element

<div id="post">
	<div class="thumb"><div>
	<div class="thumb"><div>
	<div class="thumb"><div>
	<div class="thumb"><div>

jQuery code :


Converting this to pure Javascript is fairly simple. You just need to chain document.querySelector and document.querySelectorAll methods :


Complex Case - When Outer Selector is a Collection of Elements

<div class="post">
	<div class="thumb"><div>
	<div class="thumb"><div>
<div class="post">
	<div class="thumb"><div>
	<div class="thumb"><div>

jQuery code :

// This will give all 4 inner elements with class "thumb"

Converting this to pure Javascript is not very direct. You need to find all outer matched elements, and then find inner matched elements of each of them.

// Final found elements
var found_elements = [];

// Find all the outer matched elements
var outers = document.querySelectorAll('.post');

for(var i=0; i<outers.length; i++) {
	var elements_in_outer = outers[i].querySelectorAll(".thumb");

	// document.querySelectorAll() returns an "array-like" collection of elements
	// convert this "array-like" collection to an array
	elements_in_outer = Array.prototype.slice.call(elements_in_outer);
	found_elements = found_elements.concat(elements_in_outer);

// The final 4 elements
Equivalent of jQuery Selectors in Pure Javascript
Writing jQuery closest() in Pure Javascript
Pure Javascript - Replacing an Element
Writing jQuery each() in Pure JavaScript
Adding Event Handlers on Dynamically Created Elements with Vanilla Javascript
jQuery append() in Pure Javascript
jQuery offset() in Pure Javascript