首页 > 解决方案 > 如何在不使用 ID 元素的情况下将子元素附加到父元素?

问题描述

我使用 ID 向 divTwo 添加了一个新元素。我想知道如何在 divOne 和 divTwo 中添加 p 标签而不参考它们的标识符。请帮忙。

 // create Tag 
    const createElement = (elementName) => document.createElement(elementName);
    const appendTo = (idElement, element) => document.getElementById(idElement).append(element);
    const setAttribute = (eleName, attribute, valueAttribute) => eleName.setAttribute(attribute, valueAttribute);
    const setText = (id, text) => document.getElementById(id).innerHTML = text;

    // Tag HTML

    // div one
    const divOne = createElement("div");
    const appendDivOne = appendTo("demo", divOne)
    const setIDOne = setAttribute(divOne, "id", "divOne");
    // div two 
    const divTwo = createElement("div");
    const appendDivTwo = appendTo("demo", divTwo)
    const setIDTwo = setAttribute(divTwo, "id", "divTwo");
    // child div two
    const divTwoChild = createElement("p");
    const appendDivTwoChild = appendTo("divTwo", divTwoChild);
    const setIDChildeTwo = setAttribute(divTwoChild, "id", "ChildeTwo");
    const text = setText("ChildeTwo", "childe two");
    <div id="demo"></div>

标签: javascripthtml

解决方案


您可以在创建后直接访问您的元素...例如,在使用时const divTwoChild = createElement("p");,您可以使用divTwoChild.append()...还有一个名为 的函数insertAdjacentHTML(),您可以在其中直接在给定位置添加 html 代码,请在此处阅读。以下示例(最后 3 行):

 // create Tag 
    const createElement = (elementName) => document.createElement(elementName);
    const appendTo = (idElement, element) => document.getElementById(idElement).append(element);
    const setAttribute = (eleName, attribute, valueAttribute) => eleName.setAttribute(attribute, valueAttribute);
    const setText = (id, text) => document.getElementById(id).innerHTML = text;

    // Tag HTML

    // div one
    const divOne = createElement("div");
    const appendDivOne = appendTo("demo", divOne)
    const setIDOne = setAttribute(divOne, "id", "divOne");
    // div two 
    const divTwo = createElement("div");
    const appendDivTwo = appendTo("demo", divTwo)
    const setIDTwo = setAttribute(divTwo, "id", "divTwo");
    // child div two
    const divTwoChild = createElement("p");
    const appendDivTwoChild = appendTo("divTwo", divTwoChild);
    const setIDChildeTwo = setAttribute(divTwoChild, "id", "ChildeTwo");

    divTwoChild.append("childe two"); // <-- here
    divOne.append('I am div one!'); // <-- or here
    divTwo.insertAdjacentHTML('beforeend', '<p>I am a new p in div 2!</p>'); // <-- or here
    <div id="demo"></div>


推荐阅读