9
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

.each()を使ったループ処理でオブジェクトの値を取得する

Last updated at Posted at 2016-01-07

.each()を使ったところ、上手く値の取得ができなかったので
色々なところに説明も書いてあるのですが、備忘録として。

.each()を使ってオブジェクトを取得するには

ループ
$("body").find('input[type="check"]').each(function(i, elem) {
	elem.attr("checked", true);
});

式の意味としては
"<body>内の全てのチェックボックスを順に取得、取得したチェックボックスをチェック済みにする"
となりますが、
実は、この書き方では上手く実行できません。

elemの中身はオブジェクトだと思って式を書いていますが、each文で取得した中身は「<input type='radio' id=''......./>」
の様なソースの文字列が入っています。
したがって、

ループ正解
$('body input[type="check"]').each(function(i, elem) {
  elem.checked = true;
});

上記のような書き方でセレクターとして使用すると、オブジェクトが取得でき、使えるようになります。
コメントで指摘していただいた、より簡潔な書き方に修正しました。

9
13
7

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
9
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?