この記事について
この記事では以下のメソッドを使って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属性を取得・表示