新しいHTML要素を作成し、JavaScriptを使用してDOMにそれらを追加する方法?


Originally posted here!
JavaScriptを使用して新しいHTML要素を作成するには、createElement() ドキュメントメソッドとHTMLの本文に追加します.
いくつかのテキストコンテンツで段落タグを作成し、HTMLの本体に追加したいとしましょう.
まず、段落タグを作成しましょうcreateElement() メソッド.
  • このメソッドは有効なタグ名を文字列EGとして受け取ります: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() ノードメソッド.
  • The 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);
    

    お気軽に共有する場合は、この便利な発見😃.