LoginSignup
0
0

More than 5 years have passed since last update.

jQueryのattr()で属性をセットしたら、一括でvalue値が設定される。

Posted at

自分用のメモ。

やりたかった処理は、jQueryでDOM要素を取得したら、一つの要素ごとにhref属性のvalue値を入れ替えたかった。

jQueryのattr()を使用した結果、取得したDOM要素全てのvalue値が入れ替わってしまうので、JavaScriptのsetAtribute()を使って、一つずつの要素に属性のvalue値を入れた。

index.html
!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>

<body>
   <a hret="https://www.yahoo.co.jp">yahoo</a>
   <a hret="https://www.google.co.jp">google</a>
   <a hret="https://in-sec.xyz">uno</a>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
        $(function(){
            var a = $('a');
            a.each(function(key,val){
            a[key].setAttribute('href',"https://qiita.com/"); // aタグ一つの要素ごとに処理
            a.attr('href',"https://amazon.com/"); // aタグをまとめて処理
            });
          });
    </script>
</body>

</html>
0
0
2

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