Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Using empty jQuery objects to dynamically build a selection of objects. For more info see
// 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.
// 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($'something'), visible_items) > -1) {
$invisible = $invisible.add($this);
} else {
$visible = $visible.add($this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.