javascript nodeValueでノードの値を変更する
- 作成日 2021.03.19
- 更新日 2022.08.10
- javascript
- javascript

javascriptで、nodeValueを使用して、ノードの値を変更するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 104.0.5112.81
nodeValue使い方
「nodeValue」を使用すると、ノードの値を変更することが可能です。
※ノードは、要素ノードだけでなく、改行を含んだテキストノードやコメントノードも存在します。
ノード.nodeValue
nodeValue使い方(値を取得)
※「nextSibling」は、次にあるノードを取得することができます。
<div id="main"></div>test-node<!-- コメント -->
<script>
'use strict';
const node = document.getElementById("main");
// 要素ノード
console.log(node.nextSibling) // null
// テキストノード
console.log(node.nextSibling.nodeValue) // test-node
// コメントノード
console.log(node.nextSibling.nextSibling.nodeValue) // コメント
</script>
実行結果を見ると、各種類のノードの値が取得されているが確認できます。
※要素ノードは、存在しないので「null」が返ります

次に、「nodeValue」を使用して、値を変更してます。
nodeValue使い方(値を変更)
<div id="main"></div>test-node<!-- コメント -->
<script>
'use strict';
const node = document.getElementById("main");
// テキストノード
node.nextSibling.nodeValue = 'hoge-node';
// コメントノード
node.nextSibling.nextSibling.nodeValue = 'コメント変更';
</script>
実行結果を見ると、各種類のノードの値が変更されているが確認できます。

存在しない要素を指定
存在しない要素を指定した場合は、エラーが返ります。
<div id="main"></div>test-node<!-- コメント -->
<script>
'use strict';
const node = document.getElementById("noelm");
// テキストノード
node.nextSibling.nodeValue = 'hoge-node';
// Uncaught TypeError: Cannot read properties of null (reading 'nextSibling')
// コメントノード
node.nextSibling.nextSibling.nodeValue = 'コメント変更';
</script>
存在チェックをしてから、実行するとエラーが回避できます。
'use strict';
const node = document.getElementById("noelm");
if(node !== null){
// テキストノード
node.nextSibling.nodeValue = 'hoge-node';
// Uncaught TypeError: Cannot read properties of null (reading 'nextSibling')
// コメントノード
node.nextSibling.nextSibling.nodeValue = 'コメント変更';
}
コードを少し簡潔に記述
また、以下のコードを、
const node = document.getElementById("main");
// テキストノード
node.nextSibling.nodeValue = 'hoge-node';
document.getElementByIdの省略を使用して、簡潔に記述することもできます。
node.nextSibling.nodeValue = 'hoge-node';
サンプルコード
以下は、
「変更」ボタンをクリックして、テキストノードを変更するだけの
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>
<script>
window.onload = () => {
btn.onclick = () => {
sample.nextSibling.nodeValue = '変更しました';
};
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<button id="btn"
class="bg-gradient-to-r from-green-400 to-blue-500 hover:from-pink-500 hover:to-yellow-500 text-white py-2 px-4 rounded-full mb-3 mt-4">
変更
</button>
</div>変更されるテキストノード
</div>
</body>
</html>
テキストノードが変更されていることが確認できます。

-
前の記事
ldapsearchを使用してactive directoryを検索する 2021.03.18
-
次の記事
sakuraエディタ 現在日付と現在日時をショートカットキーで入力する 2021.03.19
コメントを書く