0
0

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で指定したDOM要素の属性の取得・更新

Posted at

この記事について

この記事では以下のメソッドを使ってDOM要素の属性の取得と更新を行う

attr()
→指定したDOMU要素の取得と更新
data()
→指定したDOM要素の取得と更新

サンプルコード

以下のように取得を行う

sample.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <title>sample</title>
</head>
<body>
  <a href="hogehoge.com">googleリンク</a>
  <script>
    $(function(){
      console.log($('a').attr('href'));
    })
  </script>
</body>
</html>
/aタグのhref属性を取得してコンソールhogehoge.comを表示している

取得、および更新は以下のように第2引き数を入れる

sample.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <title>sample</title>
</head>
<body>
  <a href="hogehoge.com">googleリンク</a>
  <script>
    $(function(){
      $('a').attr('href', 'google.com');
      //aタグのhref属性を取得してgoogle.comに書き換え
      console.log($('a').attr('href'));
   //aタグのhref属性を取得してコンソールでgoogle.comを表示している
    })
  </script>
</body>
</html>

data属性は以下のように引き数を指定することによって取得ができる

sample.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <title>sample</title>
</head>
<body>
  <a href="hogehoge.com" data-sitename="googleのサイト">googleリンク</a>
  <script>
    $(function(){
      $('a').attr('href', 'google.com');
      console.log($('a').attr('href'));
      console.log($('a').data('sitename'));
    })
  </script>
</body>
</html>
//dataメソッドの引き数にsitenameと指定してdata属性を取得・表示 

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?