开发者

jQuery add elements to empty selection?

开发者 https://www.devze.com 2023-04-06 21:07 出处:网络
Why doesn\'t this work? var spans = $(); var elem = document.getElementById(\'someId\'); spans.add(elem);

Why doesn't this work?

var spans = $();
var elem = document.getElementById('someId');
spans.add(elem);

What is the proper way to start off with an empty collectio开发者_如何学Pythonn and add elements to it? I want to loop through a collection of ids and find the element on the page and add it to the matched set.


Quoting from the jQuery website:

Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method.

Hence, when you do .add() it will not save the added elements, you would have to explicitly assign the element to the newly created object i.e

var $elements = $('.elements');
$elements = $elements.add($('#anotherelement'));


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') );


I guess I don't get what you're asking. If you have an element and you want to add it to a collection, you just use the .add() method just like you've already shown. What confuses some is that this returns a new jQuery object so you would do it like this:

var spans = $();
var elem = document.getElementById('someId');
spans = spans.add(elem);

Of course, something like this would be shorter:

var spans = $();
spans = spans.add('#someId');

And, of course, you don't have to start with an empty object. You would just start with:

var spans = $('#someId');


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');


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 = $([]);


Edit: I should clarify - your code actually should work, unless you're using an older version of jQuery, in which case $() 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.
Edit 2: In response to this portion of the question: "I want to loop through a collection of ids and find the element on the page and add it to the matched set", the following code might be useful:

var ids = ['foo', 'bar', 'baz'],
    selector = $.map(ids, function(i, id) {
        return '#' + id;
    }).join(','),
    $collection = $(selector);


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.


Try

var spans = $("<span />");
var elem = $("#someId").html();
spans.append(elem).appendTo('#someAnotherId');

instead


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号