javascript - 如何在不使用 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>
解决方案
您可以在创建后直接访问您的元素...例如,在使用时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>
推荐阅读
- ionic-framework - 如何在侧面菜单的每个项目中添加自定义图标?
- wso2 - 如何在不更改偏移量的情况下更改 WSO2 APIM 中的端口
- vba - 自动打开来自内部电子邮件地址的传入邮件
- ruby-on-rails - Rails 5服务器应用程序中的重复请求信息日志
- cassandra - 具有 TTLed 插入和 TTLed 更新的数据的时间窗口压缩策略
- angular - 我需要在没有图标 angular 8 的 mat-tab 中添加 matTooltip,并且使用了角度材料
- c++ - 有什么方法可以检测我的类的对象是否是在堆栈上创建的?
- java - 如何增加 Firestore SDK 查询流的超时时间
- tensorflow - 如何合并两个或更多训练的权重?
- javascript - 如何阻止图像的宽度在 div 内拉伸?