Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an empty jQuery result [duplicate]

Edit: As of jQuery 1.4, using $() will work as described below.


I need to loop through an array and create a number of elements which I want to have in a single jQuery result object.

for (var i = 0; i < 10; ++i) {
    $myJQueryObj = $myJQueryObj.add($("<span>blahblah</span>"));
}

The problem with this, however, is that you need a jQuery object to begin with, and you obviously want to start it empty. In the above example, how should I initialise $myJQueryObj ?

The following examples do not work, as they all select the document object:

$('')
$()
$(null)
$(false)

These do work... but...

$('#nonExistantElement')  // yuck
$().slice(0,0)            // surely there's a nicer way?

Is there a better way?

like image 726
nickf Avatar asked Jan 05 '10 00:01

nickf


2 Answers

Yep. Try $([]). The reason $() doesn't work is because that jQuery expects a context, and without any supplied, will default to document as the context. Many things depend on this assumption being true, so changing $() to mean "give me the empty set" would be problematic at best.

like image 139
John Feminella Avatar answered Oct 21 '22 23:10

John Feminella


Ah, I figured it out just after I wrote the question. Here's what I found, in case anyone else is interested:

$([])
like image 28
nickf Avatar answered Oct 22 '22 00:10

nickf