Finding DOM Elements: JQuery vs. Native JavaScript

Omar Barguti
2 min readApr 20, 2021

--

Finding Descendants in JQuery
In JQuery, you can use the built in ‘find’ function to search trough query results and select specific descendants. The find function accepts a CSS selector and it is straight forward to use:

// To search the 'mainDiv' descendants and find all paragraphs with the class 'large' on them: 
$(".mainDiv").find("p.large");

Finding Descendants in Native JavaScript
Searching for descendant elements in JavaScript is not so trivial. JQuery does a lot under the covers when performing such a task. Initially, a call to ‘querySelectorAll’ is triggered to perform the top level search and return a nodeList. Next, the ‘NodeList’ is converted to a JavaScript array. Next, each entry in the array is passed into a new call to ‘querySelectorAll’ and the results from all the array elements are concatenated into a single result list. Below is an example on how to do this:

// Finds all the divs in the HTML document
var divs = document.querySelectorAll("div")
// Declares an empty array to hold all the descendant spans
var spans = [];
// Loop through the divs NodeList and for each entry, invoke the querySelectorAll function
// The result of each call is split and appended to the spans function
[].forEach.call(divs, function(div) {
spans = spans.concat([].slice.call(div.querySelectorAll("span")));
});

It might be a good idea to move this logic into a custom JavaScript extensions library.

Finding Ancestors in JQuery
In JQuery, finding the nearest ancestor is trivial. The ‘closest()’ function can be invoked and it accepts a CSS selector or a function.

$("#mySpan").closest("div");

Finding Ancestors in Native JavaScript
There is no easy way to find an element’s ancestor in native JavaScript. In order for this to be done, it is probably a good idea to write a custom function that loops through elements in the ancestry tree. This function should be added to the prototype of the Element class for ease of re-usability:

// Check is the 'Closest' function is not already implemented
if(Element && !Element.prototype.closest) {

Element.prototype.closest = function(selector, filter) {
var element = this;
var foundAncestor;
// If the passed in filter is a CSS string, execute it
filter = (typeof filter === 'string' ? document.querySelector(filter) : filter);
while(element instanceofElement && !(foundAncestor = element.matches(selector)) && element !== filter) {
element = element.parentNode;
}
return foundAncestor ? element : null;
};
}
// You can call it like:
document.getElementById("#mySpan").closest("div");

--

--

Omar Barguti
Omar Barguti

Written by Omar Barguti

An enthusiastic architect and full-stack developer with many years working with enterprise software and cloud services in multiple domains.

No responses yet