DOMを変更する方法

前書き

Understanding the DOMシリーズの前回の2回の記事では、https://www.digitalocean.comを学びました。 / community / tutorials / how-to-access-elements-in-the-dom [DOMの要素にアクセスする方法]およびhttps://www.digitalocean.com/community/tutorials/how-to-traverse-the- dom [DOMをトラバースする方法]。 この知識を使用して、開発者はクラス、タグ、ID、セレクターを使用してDOMのノードを検索し、親、子、兄弟のプロパティを使用して相対ノードを検索できます。

DOMをさらに使いこなすための次のステップは、ノードの追加、変更、置換、削除の方法を学ぶことです。 To Doリストアプリケーションは、DOMの要素を作成、変更、削除できるようにする必要があるJavaScriptプログラムの実用的な例の1つです。

このチュートリアルでは、新しいノードを作成してDOMに挿入し、既存のノードを置き換え、ノードを削除する方法について説明します。

新しいノードの作成

静的Webサイトでは、HTMLを直接「+ .html 」ファイルに記述することにより、要素がページに追加されます。 動的なWebアプリでは、要素とテキストがJavaScriptで追加されることがよくあります。 ` createElement()`および ` createTextNode()+`メソッドは、DOMに新しいノードを作成するために使用されます。

Property/Method Description

createElement()

Create a new element node

createTextNode()

Create a new text node

node.textContent

Get or set the text content of an element node

node.innerHTML

Get or set the HTML content of an element

まず、 `+ index.html`ファイルを作成して、新しいプロジェクトディレクトリに保存します。

index.html

<!DOCTYPE html>
<html lang="en">

 <head>
   <title>Learning the DOM</title>
 </head>

 <body>
   <h1>Document Object Model</h1>
 </body>

</html>

ページ上の任意の場所を右クリックし、「検査」を選択して開発者ツールを開き、* https://www.digitalocean.com/community/tutorials/how-to-use-the-javascript-developer-console [コンソール]*。

+ document`オブジェクトで + createElement()+ を使用して、新しい + p + `要素を作成します。

const paragraph = document.createElement('p');

_Console_でテストできる新しい「+ p +」要素を作成しました。

console.log(paragraph)
Output<p></p>

`+ paragraph `変数は空の ` p `要素を出力しますが、これはテキストなしではあまり役に立ちません。 要素にテキストを追加するために、 ` textContent +`プロパティを設定します。

paragraph.textContent = "I'm a brand new paragraph.";
console.log(paragraph)
Output<p>I'm a brand new paragraph.</p>

`+ createElement()`と ` textContent +`の組み合わせにより、完全な要素ノードが作成されます。

要素のコンテンツを設定する別の方法は、 `+ innerHTML +`プロパティを使用することです。これにより、要素にHTMLとテキストを追加できます。

paragraph.innerHTML = "I'm a paragraph with <strong>bold</strong> text.";

`+ createTextNode()+`メソッドでテキストノードを作成することもできます。

const text = document.createTextNode("I'm a new text node.");
console.log(text)
Output"I'm a new text node."

これらのメソッドを使用して、新しい要素とテキストノードを作成しましたが、ドキュメントに挿入されるまでウェブサイトのフロントエンドに表示されません。

DOMへのノードの挿入

フロントエンドで作成した新しいテキストノードと要素を表示するには、それらを `+ document `に挿入する必要があります。 メソッド ` appendChild()`および ` insertBefore()`は、親要素の先頭、中間、または末尾にアイテムを追加するために使用され、 ` replaceChild()+`は古いノードを置き換えるために使用されます新しいノードで。

Property/Method Description

node.appendChild()

Add a node as the last child of a parent element

node.insertBefore()

Insert a node into the parent element before a specified sibling node

node.replaceChild()

Replace an existing node with a new node

これらの方法を実践するために、HTMLでTo Doリストを作成しましょう。

todo.html

<ul>
 <li>Buy groceries</li>
 <li>Feed the cat</li>
 <li>Do laundry</li>
</ul>

ブラウザにページをロードすると、次のようになります。

image:https://assets.digitalocean.com/articles/eng_javascript/dom/to-do-1.png [DOMスクリーンショット1]

To Doリストの最後に新しいアイテムを追加するには、上記の「新しいノードの作成」セクションで行ったように、最初に要素を作成してテキストを追加する必要があります。

// To-do list ul element
const todoList = document.querySelector('ul');

// Create new to-do
const newTodo = document.createElement('li');
newTodo.textContent = 'Do homework';

新しいTo Doの完全な要素ができたので、 `+ appendChild()+`を使用してリストの最後に追加できます。

// Add new todo to the end of the list
todoList.appendChild(newTodo);

新しい「+ li 」要素が「 ul +」の末尾に追加されていることがわかります。

todo.html

<ul>
 <li>Buy groceries</li>
 <li>Feed the cat</li>
 <li>Do laundry</li>
 <li>Do homework</li>
</ul>

image:https://assets.digitalocean.com/articles/eng_javascript/dom/to-do-2.png [DOMスクリーンショット2]

優先度の高いタスクを実行する必要があり、リストの先頭に追加したい場合があります。 `+ createElement()+`は1つの要素のみを作成し、再利用できないため、別の要素を作成する必要があります。

// Create new to-do
const anotherTodo = document.createElement('li');
anotherTodo.textContent = 'Pay bills';

`+ insertBefore()+`を使用して、リストの先頭に追加できます。 このメソッドは2つの引数を取ります。1つ目は追加する新しい子ノードで、2つ目は新しいノードの直後に続く兄弟ノードです。 つまり、次の兄弟ノードの前に新しいノードを挿入します。 これは、次の擬似コードに似ています。

parentNode.insertBefore(newNode, nextSibling);

To Doリストの例では、リストの最初の子要素の前に新しい `+ anotherTodo `要素を追加します。これは現在、 ` Buy grocerries +`リストアイテムです。

// Add new to-do to the beginning of the list
todoList.insertBefore(anotherTodo, todoList.firstElementChild);

todo.html

<ul>
 <li>Pay bills</li>
 <li>Buy groceries</li>
 <li>Feed the cat</li>
 <li>Do laundry</li>
 <li>Do homework</li>
</ul>

image:https://assets.digitalocean.com/articles/eng_javascript/dom/to-do-3.png [DOMスクリーンショット3]

リストの先頭に新しいノードが正常に追加されました。 これで、ノードを親要素に追加する方法がわかりました。 次に行うことは、既存のノードを新しいノードに置き換えることです。

既存のTo Doを変更して、ノードを置き換える方法を示します。 新しい要素を作成する最初のステップは同じままです。

const modifiedTodo = document.createElement('li');
modifiedTodo.textContent = 'Feed the dog';

`+ insertBefore()`と同様に、 ` replaceChild()+`は次の擬似コードに示すように、新しいノードと置換されるノードの2つの引数を取ります。

parentNode.replaceChild(newNode, oldNode);

リストの3番目の要素の子を変更されたTo Doに置き換えます。

// Replace existing to-do with modified to-do
todoList.replaceChild(modifiedTodo, todoList.children[2]);

todo.html

<ul>
 <li>Pay bills</li>
 <li>Buy groceries</li>
 <li>Feed the dog</li>
 <li>Do laundry</li>
 <li>Do homework</li>
</ul>

image:https://assets.digitalocean.com/articles/eng_javascript/dom/to-do-4.png [DOMスクリーンショット4]

+ appendChild()++ insertBefore()+、および `+ replaceChild()+`の組み合わせにより、DOMの任意の場所にノードと要素を挿入できます。

DOMからノードを削除する

これで、要素を作成し、DOMに追加し、既存の要素を変更する方法がわかりました。 最後のステップは、DOMから既存のノードを削除することを学ぶことです。 子ノードは親から `+ removeChild()`で削除でき、ノード自体は ` remove()+`で削除できます。

Method Description

node.removeChild()

Remove child node

node.remove()

Remove node

上記のToDoの例を使用して、完了したアイテムを削除します。 宿題を完了したら、 `+ removeChild()`を使用して、たまたまリストの最後の子である ` Do homework +`アイテムを削除できます。

todoList.removeChild(todoList.lastElementChild);

todo.html

<ul>
 <li>Pay bills</li>
 <li>Buy groceries</li>
 <li>Feed the dog</li>
 <li>Do laundry</li>
</ul>

image:https://assets.digitalocean.com/articles/eng_javascript/dom/to-do-5.png [DOMスクリーンショット5]

別の方法は、ノードで直接 `+ remove()+`メソッドを使用して、ノード自体を削除することです。

// Remove second element child from todoList
todoList.children[1].remove();

todo.html

<ul>
 <li>Pay bills</li>
 <li>Feed the dog</li>
 <li>Do laundry</li>
</ul>

image:https://assets.digitalocean.com/articles/eng_javascript/dom/to-do-6.png [DOMスクリーンショット6]

+ removeChild()+`と `+ remove()+`の間で、DOMから任意のノードを削除できます。 DOMから子要素を削除する別の方法は、親要素の `+ innerHTML +`プロパティを空の文字列( `+" "+)に設定することです。 これは明示的ではないため推奨される方法ではありませんが、既存のコードで見ることができます。

結論

このチュートリアルでは、JavaScriptを使用して新しいノードと要素を作成し、DOMに挿入し、既存のノードと要素を置き換えて削除する方法を学びました。

DOMシリーズを理解するのこの時点で、DOMの要素にアクセスする方法を知っています。 DOMのノード、およびDOM自体の変更。 JavaScriptを使用して基本的なフロントエンドWebアプリを作成することに自信を持つことができます。