如何在不使用ID元素的情况下将子项附加到父项

  • 本文关键字:情况下 元素 ID javascript html
  • 更新时间 :
  • 英文 :


我使用了一个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>

您似乎正在尝试附加到div1,根据您的代码,div1将是中的第一个元素。如果你想附加一个P标签,你可以做:

const divOneChild = createElement("p")
const appendP = appendTo(document.getElementById("demo").firstChild, divOneChild)

您可以在创建后直接访问元素。。。例如,当使用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>

相关内容

  • 没有找到相关文章

最新更新