jQuery attrメソッドを使って対象要素のid属性の値を取得する方法
環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1
構文
const 変数名 = $('対象要素’).attr('id’);
attrメソッドを使って対象要素のid属性を取得します。
形式
const 変数名 = $('div’).attr('id’);
このdiv要素に対して「attr('id’)」を記述することで、id属性の値を取得します。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
const result = $('div').attr('id');
console.log( result );
});
</script>
</head>
<body>
<div id="city">東京</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
const result = $('div').attr('id');
console.log( result );
});
</script>
</head>
<body>
<div id="city">東京</div>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ const result = $('div').attr('id'); console.log( result ); }); </script> </head> <body> <div id="city">東京</div> </body> </html>
実行結果
コンソールログに下記メッセージを出力します。
city