LoginSignup
36
35

More than 5 years have passed since last update.

空のjQueryオブジェクトを作って要素を追加する方法

Last updated at Posted at 2013-01-10

空のjQueryオブジェクトは$()で作ることができる

要素の追加は.add()だが、その語感から破壊的メソッドと勘違いしこんなことをしがち。

var $list = $();
var i = 3;
while (i--) {
  $list.add($('<div>'));
}
console.log($list.length);    // 0

実は.add()は破壊的ではなく、新しいjQueryオブジェクトが戻ってくるのでこちらが正解。

var $list = $();
var i = 3;
while (i--) {
  $list = $list.add($('<div>'));
}
console.log($list.length);    // 3
36
35
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
35