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>
<div>

jQuery code :

$("#post").find(".thumb")

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

document.querySelector("#post").querySelectorAll('.thumb')

Complex Case - When Outer Selector is a Collection of Elements

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

jQuery code :

// This will give all 4 inner elements with class "thumb"
$(".post").find(".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
console.log(found_elements);
I'm available for freelancing
If you've liked this article, you'll probably like my code too.

From short code snippets to complete web applications, I code in Javascript & PHP
Low Prices from $20, Fast Delivery Time
jQuery to Pure Javascript, Part 1 : Selectors
Writing jQuery closest() in Pure Javascript
I'm available for freelancing
If you've liked this article, you'll probably like my code too.

From short code snippets to complete web applications, I code in Javascript & PHP
Low Prices from $20, Fast Delivery Time