1
3

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.

JQueryでidをつける

Posted at

idをJQueryで追加する

以前、与えられたhtmlファイルに手でidを100個くらい追加していたが、デザイン変わったらやり直すのかーと思うと悲しくなったので、
idは別途追加したいと思った。

index.htmlのbodyの中身は以下

index.html
<dl id="body">
  <button>hoge</button>
  <button>fuga</button>
  <button>hoga</button>
</dl>

このファイルに以下のjsファイルを読ませる

menu.js
$(function () {
    $('button').attr('id', 'hoge');
});

するとindex.htmlにidが追加される。

index.html
<dl id="body">
  <button id="hoge">hoge</button>
  <button id="hoge">fuga</button>
  <button id="hoge">hoga</button>
</dl>

idが振られた。

    $('button').attr('id', 'hoge');

と書くと、buttonという要素に新たな要素'id'を要素値'hoge'で追加してくれる。

でも俺がやりたいのは、バラバラのidを付けることなので、menu.jsを変更

menu.js
$(function () {
    $('button').eq(0).attr('id', 'hoge');
    $('button').eq(1).attr('id', 'fuga');
    $('button').eq(2).attr('id', 'hoga');
});

.eq()とすると、何番目かも指定できる。
するとidも変わる。

index.html
<dl id="body">
  <button id="hoge">hoge</button>
  <button id="fuga">fuga</button>
  <button id="hoga">hoga</button>
</dl>

バラバラのidが付けられた。
今回はこれで良いが、以前の100個id手打ちはこのやり方では解決しないんじゃないかなぁ...

おわり

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?