Why doesn\'t this work?
var spans = $();
var elem = document.getElementById(\'someId\');
spans.add(elem);
What is the proper way to start
If you're looking to push
or add
items selected from a jQuery object, you could also do this:
var $els = $(),
$someEls = $(".some-els");
$els.push.apply($els, $someEls);
Just another way to do it.
What you actually want to do is use jQuery to it's full potential. You can use selectors to grab and create the collection right away. Your three lines above becomes one line:
var spans = $('#someId');
to add more ids to the collection, you can separate them with commas:
var spans = $('#someId1, #someid2, #someid3');
While this doesn't directly answer the question of "how to append to an existing jQuery selection", I have a work-around for this particular use-case.
You can pass an array of DOM elements to jQuery, and it will create a jQuery selection out of them.
var spansArray = [];
var elem = document.getElementById('someId');
spansArray.push(elem);
var spans = $(spansArray);
I can't think of any reason why you would need to add each element to the jQuery selection one-at-a-time, as opposed to all-at-once, so this should be a "drop-in-replacement" for your use case. In theory, this must also prove more efficient, as jQuery's .add()
is ultimately just calling .push()
on some array behind the scenes.
There may be better ways to do what you're trying, but if you just want to create an empty jQuery object, use this:
var $foo = $([]);
$()
would create a collection containing the document
object. In newer versions, however, there's nothing wrong with that. The code snippet I pasted above is just something that should work in older versions and newer versions of jQuery.
var ids = ['foo', 'bar', 'baz'],
selector = $.map(ids, function(i, id) {
return '#' + id;
}).join(','),
$collection = $(selector);
The .add()
method returns a new jQuery object, so you'd need to overwrite the old one:
spans = spans.add( elem );
...or since you're adding DOM elements, you can modify the existing jQuery object with .push()
.
spans.push( elem );
EDIT: Changed .pushStack()
to .push()
, though I don't know if .push()
is officially supported.
You could use .pushStack()
to add a collection though.
spans = spans.pushStack( [elem] );
or
spans = spans.pushStack( document.getElementsByTagName('div') );
The reason your code doesn't work is because add
does not change the collection, it returns a new jQuery object with the new elements in it. If you wanted, you could instead say spans = spans.add(elem);
, but what you're doing is unnecessary: the beauty of jQuery is that it makes this sort of imperative programming unnecessary. Look at helloandre's answer for a much easier way to accomplish your goal.
It's like the following, if this makes sense:
var x = [1, 2, 3];
x.concat(4);
console.log(x); // [1, 2, 3] -- concat does not mutate the original array