LoginSignup
1
1

More than 3 years have passed since last update.

jQueryで要素の属性を指定する方法 attr()

Posted at
index.html
<a>リンク</a>

aタグに対してリンク先をjQueryで動的に選択したい場合は attr()を使います。

main.js
$('a').attr('href','./sample.html');

このように書くと動的にhref属性を指定することができます。
また、このattr()ではhref以外の属性も指定が可能で
例えばid属性も指定することができます。

main.js
$('a').attr('id','link');

複数の属性を指定することも可能です。
その場合はオブジェクト型で指定してあげれば大丈夫です。

main.js
$('a').attr({
  id: 'link',
  href: './sample.html',
  name: 'sample'
});

このように書いてあげると自由に属性値を指定してあげることができます。
ぜひ使ってみてください!

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