本記事では、jQueryでname属性の取得・追加・変更する方法について分かりやすく解説しています。
あわせて読みたい


【jQuery】name属性で指定した要素を取得する方法
本記事では、jQueryでname属性で指定した要素を取得する方法について解説しています。 【name属性で指定した要素を取得】 name属性で指定した要素を取得する記述は以下…
JavaScriptの学習におすすめ書籍
1冊ですべて身につくJavaScript入門講座

メリット
- 誰でも分かるように嚙み砕いて説明してくれる
- アニメーションの知識が深く学べる
- 1つのWebサイトを作りながら学べる


Amazon Kindle Unlimitedに登録すると、月額980円で読み放題だからオススメだよ!



初回30日間は無料だから、まだ登録したことのない人はぜひ試してみてね!
全プログラマー必見!
変数名/関数名にもう悩まない!
変数名/関数名にもう悩まない!
リーダブルコード


メリット
- 美しいコードが書けるが自然と書けるようになる
- 他の開発者が理解しやすいコードになる
著:Dustin Boswell, 著:Trevor Foucher, 解説:須藤 功平, 翻訳:角 征典
¥2,640 (2023/07/23 02:48時点 | Amazon調べ)


目次
name属性の操作



先輩!jQueryでname属性の操作方法を教えてください!



了解!name属性の取得・追加・変更する方法を別々に紹介するね!
name属性の取得
name属性を取得するには、attr()メソッドを使います。基本的な使い方は以下のとおりです。
/* フォーマット */
$('セレクタ').attr('name');
/* 例
<input type="text" name="sample" />
*/
$('input').attr('name');



name属性を取得するサンプルコードを用意したので、動作確認してみましょう!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<input type="text" name="sample" />
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="index.js"></script>
</body>
</html>
const getName = $('input[type="text"]').attr("name");
console.log(getName); // sample
name属性の追加・変更



name属性の追加・変更は記述方法が同じだからまとめて紹介するね!
name属性の追加・変更も、先ほど紹介したattr()メソッドを使用します。異なる点は、追加と変更では第二引数も指定することです。基本的な使い方は以下のとおりです。
/* フォーマット */
$('セレクタ').attr('name', '値');
/* 例(name属性の追加)
<input type="text" />
*/
$('input').attr('name', 'sample1');
/* 例(name属性の変更)
<input type="text" name="sample1" />
*/
$('input').attr('name', 'sample2');
- 第一引数:属性名を指定。name属性なので、nameと記述します。
- 第二引数:属性名にセットする値を指定。



name属性の追加・変更するサンプルコードを用意したので、動作確認してみましょう!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<input type="text" />
<input type="search" name="sample1" />
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="index.js"></script>
</body>
</html>
/* name属性の追加 */
const $inputText = $('input[type="text"]');
$inputText.attr("name", "sample1");
console.log($inputText); // <input type="text" name="sample1">
/* name属性の変更 */
const $inputSearch = $('input[type="search"]');
$inputSearch.attr("name", "sample2");
console.log($inputSearch); // <input type="search" name="sample2">