jQuery attrメソッドを使って対象要素のid属性を変更する

環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1

構文
const 変数名 = $('div’).attr('id’,変更後値);
attrメソッドを使って対象要素のid属性の値を変更します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!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','cityname');
console.log( result[0] );
});
</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','cityname'); console.log( result[0] ); }); </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','cityname');
   console.log( result[0] );
});
</script>
</head>
<body>

<div id="city">東京</div>

</body>
</html>

実行結果
id属性値を「cityname」に変更します。
<div id="cityname">東京</div>

jQuery

Posted by arkgame