Working with empty jQuery objects to build dynamic selectors

This is one of those techniques that you don’t really think you need until you find yourself in a situation where you do. This definitely isn’t a hammer and more often than not, you can select what you need in a single selector via jQuery or through the use of the built-in .filter() method but when writing more complex jQuery, this technique can come in handy.

The technique I’m referring to is the ability to kick off with an empty jQuery object and build it up dynamically. It’s not something I use very often but it has come in handy so I figure I’d throw up an example.

// This demonstrates how we can kick things off with empty jQuery
// objects and dynamically build them using the .add() method.
// Note that using the add() method creates a new jQuery object
// containing whatever was already in it along with our newly added
// items. This is a contrived set of examples and the use case for
// this is quite nuanced but this hopefully illustrates how you might
// utilise empty jQuery objects.
// Create an empty jQuery object. We can now built up a jQuery object
// using jQuery's .add() method.
let $selection = $();
// Let's run a loop that adds new elements to our empty selector
// on the fly.
for (let i = 0; i < 5; i++) {
$selection = $selection.add($(`<p>Some selection ${i}</p>`));
}
// It is also possible to select DOM elements and add the results of
// those selections to our initial object.
$selection.add($('.some-dom-element'));
// We can also loop through a set of matched elements, handle them
// conditionally, and divide them into groups.
let $visible = $(), $invisible = $(), visible_items = ['one', 'two', 'three'];
$('.elements').each(function () {
let $this = $(this);
if ($.inArray($this.data('something'), visible_items) > -1) {
$this.hide();
$invisible = $invisible.add($this);
} else {
$visible = $visible.add($this);
$this.show();
}
});

Need a website? Let's talk.

From website design & SEO through to custom WordPress plugin development. I transform ideas into dynamic, engaging, and high-performing solutions.
Subscribe to get the latest insights & updates in the world of web and how it impacts your business and website.
© 2024 Phil Kurth  |  All rights reserved.