Web API DOMの操作

DOMの操作

上の画像は、 DOMのテキストを操作したものです。 インターフェイスは、 document.querySelector()メソッド、 document.createElement()メソッド、 document.createTextNode()メソッド、 element.appendChild()メソッド を使用しています。

htmlのコードは次の様になります。

<body> <section> <p>DOM</p> </section> <script> const S = document.querySelector('section'); const P1 = document.createElement('p'); P1.textContent = 'Hello World'; S.appendChild(P1); const T = document.createTextNode('--text文'); const P2 = document.querySelector('p'); P2.appendChild(T); </script> </body>

インターフェイスメソッド

上ののコードで使用している、 document.querySelector()メソッドと、 document.createElement()メソッドは、 「Web APIとは」のページで説明しましたので、 「Web APIとは」こちらを参考にしてください。 document.createTextNode()メソッドは、 新しい Text ノードを生成します。 構文は var text = document.createTextNode(data); data: テキストノードの中に入れるデータが入った文字列。 戻り値は、 text: Text ノードです。 element.appendChild()メソッドは、 特定の親ノードの子ノードリストの末尾に、 ノードを追加します。 戻り値は追加した子ノードです。 以上です。