新しいHTML要素を作成し、JavaScriptを使用してDOMにそれらを追加する方法?
4813 ワード
Originally posted here!
JavaScriptを使用して新しいHTML要素を作成するには、
いくつかのテキストコンテンツで段落タグを作成し、HTMLの本体に追加したいとしましょう.
まず、段落タグを作成しましょう このメソッドは有効なタグ名を文字列EGとして受け取ります:
このメソッドは有効な文字列を受け取ります.
そのためには The
を使いましょう
お気軽に共有する場合は、この便利な発見😃.
JavaScriptを使用して新しいHTML要素を作成するには、
createElement()
ドキュメントメソッドとHTMLの本文に追加します.いくつかのテキストコンテンツで段落タグを作成し、HTMLの本体に追加したいとしましょう.
まず、段落タグを作成しましょう
createElement()
メソッド.p
, div
, など// create paragraph tag
const paragraph = document.createElement("p");
では、テキストコンテンツを作成しましょうcreateTextNode()
ドキュメントメソッド.// create paragraph tag
const paragraph = document.createElement("p");
// create some text
const textNode = document.createTextNode("Hello World!");
テキストコンテンツを作成した後、段落ノードにテキストコンテンツノードをアタッチする必要があります.そのためには
appendChild()
ノードメソッド.appendChild()
メソッドは有効なノード参照を受け入れます.// create paragraph tag
const paragraph = document.createElement("p");
// create some text
const textNode = document.createTextNode("Hello World!");
// add text node to paragragh node
paragraph.appendChild(textNode);
最後に、段落タグ全体をHTML自身の本体に付ける必要があります.を使いましょう
appendChild()
ノードメソッドを再度HTML本体ノードにアタッチします.// create paragraph tag
const paragraph = document.createElement("p");
// create some text
const textNode = document.createTextNode("Hello World!");
// add text node to paragragh node
paragraph.appendChild(textNode);
// get the HTML body tag
const body = document.querySelector("body");
// attach paragraph to the body tag.
body.appendChild(paragraph);
お気軽に共有する場合は、この便利な発見😃.
Reference
この問題について(新しいHTML要素を作成し、JavaScriptを使用してDOMにそれらを追加する方法?), 我々は、より多くの情報をここで見つけました https://dev.to/melvin2016/how-to-create-new-html-elements-and-add-them-to-dom-using-javascript-87aテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol