javascript name属性の値を変更する
- 作成日 2023.02.25
- javascript
- javascript
javascriptで、name属性の値を変更するサンプルコードを記述してます。「setAttribute」を使って「name」に変更したい値を設定します。
環境
- OS windows11 pro 64bit
- ブラウザ chrome 110.0.5481.178
name属性の値を変更
name属性の値を変更するには
1. 対象の要素を取得
2. 「setAttribute」で「name」に変更したい値を設定
で可能です。
<form id="frm">
<input type="text" id="txt" name="foo" />
</form>
<script>
const elm = document.getElementById('txt');
elm.setAttribute('name', 'bar');
</script>
実行結果
また、「name」属性の値を取得するには「getAttribute」を使用します。
<form id="frm">
<input type="text" id="txt" name="foo" />
</form>
<script>
const elm = document.getElementById('txt');
elm.setAttribute('name', 'bar');
console.log( elm.getAttribute('name') ); // bar
</script>
存在しない要素
存在しない要素を指定するとエラーとなります。
<form id="frm">
<input type="text" id="txt" name="foo" />
</form>
<script>
const elm = document.getElementById('noelm');
elm.setAttribute('name', 'bar');
// Uncaught TypeError: Cannot read properties of null (reading 'setAttribute')
</script>
存在チェックを行うとエラーは回避できます。
<form id="frm">
<input type="text" id="txt" name="foo" />
</form>
<script>
const elm = document.getElementById('noelm');
if(elm !== null){
elm.setAttribute('name', 'bar');
};
</script>
複数のname属性
複数のname属性に値を設定する場合は、「forEach」を使用して設定します。
<form id="frm">
<input type="checkbox" name="chk" />
<input type="checkbox" name="chk" />
<input type="checkbox" name="chk" />
</form>
<script>
const elm = document.getElementsByName('chk');
console.log(elm); // NodeList(3) [input, input, input]
[...elm].forEach(
(v)=>{v.setAttribute('name', 'bar')}
);
</script>
実行結果
サンプルコード
以下は、
「 実行 」ボタンをクリックすると、フォームに入力された値を自身のname属性の値として使用するサンプルコードとなります。
※cssには「bootstrap material」を使用してます。関数はアロー関数で記述してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<!-- MDB -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>
<body>
<div class="container text-center w-50" style="margin-top:200px">
<h2><span class="badge badge-success">結果</span></h2>
<form>
<div class="form-group">
<input type="text" id="setData" name="foo">
</div>
</form>
<button type="button" onclick="setName()" class="btn btn-success mt-1">
実行
</button>
</div>
<script>
const setName = () => {
// 値を設定
setData.setAttribute('name', setData.value);
// 結果を表示
document.getElementsByClassName('badge')[0].textContent = setData.getAttribute('name');
}
</script>
</body>
</html>
設定されていることが確認できます。
-
前の記事
docker-compose.yml エラー「found a tab character that violates indentation」が発生した場合の対処法 2023.02.24
-
次の記事
gmail メッセージの送信を行うショートカットキー 2023.02.25
コメントを書く