jQuery add elements to empty selection?

后端 未结 9 1382
一向
一向 2020-12-29 18:52

Why doesn\'t this work?

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

What is the proper way to start

9条回答
  •  醉梦人生
    2020-12-29 19:39

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

提交回复
热议问题