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?
Considering how jQuery handles DOM elements passed to
jQuery(), this should be fine: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.mergewhich 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 thelengthattribute. 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).