Dmitry Druganov
Dmitry Druganov

Reputation: 2368

Change jQuery set without producing a new jQuery object

I need to replace the only item in a jQuery set, which contains only one element. I receive this jQuery object as an argument to my function. So I can't just do the following:

myJQuerySet = myJQuerySet.replaceWith( anotherDomElement );

I found that this trick do the job:

myJQuerySet[0] = anotherDomElement;

But is it correct and safe?

Upvotes: 3

Views: 113

Answers (3)

Felix Kling
Felix Kling

Reputation: 816770

Considering how jQuery handles DOM elements passed to jQuery(), this should be fine:

(function($) {
    $.fn.set = function(element) {
        if(element.nodeType) {
            this.context = this[0] = element;
            this.length = 1;
        }
        return this;
    };
}(jQuery));

Not sure about the consequences if several elements have been selected though. You might also want to check the current length of the jQuery object.

Also interesting in this regard is jQuery.merge which is often used when new sets are created or elements are added. It is really just copying all numerical properties from one argument to the other and updating the length attribute. So what you are doing seems to be fine, but will of course break when jQuery changes the internal representation (if they do that at all).

Upvotes: 2

Alnitak
Alnitak

Reputation: 339917

You've specified that there's exactly one item in this jQuery object.

You've also specified that you have exactly one element that you want to put into it.

So what's actually wrong with creating a new jQuery object?

$(myElement)

It's the simplest degenerate use of the jQuery constructor, and the only reason I can think of not to use it is if you are micro-optimising. Don't.

Upvotes: 0

Matt
Matt

Reputation: 75317

The only time I can see this being a problem is if the jQuery set was empty; the length attribute won't be updated. If you can guarantee that the size will be at least 1, then you're fine.

Otherwise, you might want to do something like this;

myJQuerySet[0] = anotherDomElement;
myJQuerySet.length = myJQuerySet.length || 1; 

Upvotes: 1

Related Questions