jQuery add elements to empty selection?

后端 未结 9 1458
一向
一向 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:40

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

提交回复
热议问题