构建一个JS函数来动态创建HTML元素并将它们嵌套在彼此内部
Building a JS Function to dynamically create HTML elements and nest them inside each other
我创建了以下函数动态创建HTML元素,并将它们附加到我想要的任何位置。控制台在运行时不会记录任何错误,但第二个元素(<p>
)不写入文档。
我认为这个错误与"createdDiv"变量有关,但我还无法找出出了什么问题。
如有任何帮助,我们将不胜感激!
//Array of elements to be created
var createdElements = [
[ 'div', 'Class0', 'ID0'],
['p', 'Class1', 'ID1']
];
//function to create and append elements to document
function createHTML( typeOfCreatedElement ,createdElementClass, createdElementId, locationForCreatedElement ){
var createdElement = document.createElement( typeOfCreatedElement );
createdElement.className = createdElementClass;
createdElement.id = createdElementId;
locationForCreatedElement['appendChild']( createdElement );
return createdElement;
}
//run function 2x;
//createdDiv successfully writes to the document, but createdParagraph disappears into a black hole...
var createdDiv = createHTML( createdElements[0][0], createdElements[0][1], createdElements[0][2], document.body );
var createdParagraph = createHTML( createdElements[1][0], createdElements[1][1], createdElements[1][2], createdDiv );
您可以尝试使用此更新createHTML方法()吗
function createHTML( typeOfCreatedElement ,createdElementClass, createdElementId, locationForCreatedElement ){
var createdElement = document.createElement( typeOfCreatedElement );
createdElement.className = createdElementClass;
createdElement.id = createdElementId;
createdElement.innerHTML = "this is a sample text for element type " + typeOfCreatedElement;
locationForCreatedElement.appendChild( createdElement ); //line that I have changed.
return createdElement;
}
appendChild是一个方法,而不是属性。
相关文章:
- 如果类不是一个选项,如何在使用 jQuery 时控制(避免)嵌套 html 元素的样式
- 如何在html angular中显示嵌套的json元素
- KnockoutJS:为虚拟元素使用嵌套的条件if语句
- 滚动所有嵌套的滚动条,使HTML元素进入视图
- 选择具有重新成角度或成角度的嵌套阵列元素
- 多个嵌套元素上的jQuery.text('')
- jQuery对嵌套在<李>并且<a>元素,同时离开父<ul>打开
- 量角器 - 根据条件识别嵌套下拉元素时超时
- 使用 jquery 更改嵌套在随机 html 元素中的 html 元素
- 如何在不丢失格式的情况下连续淡入() 元素文本的每个字符,包括嵌套元素
- 如何选择嵌套了两个 .each() 函数的多个元素
- 选择嵌套元素
- iframe作为pre元素的嵌套元素
- 如何在同一个表中显示这两个嵌套ng重复的元素
- Protractor-如何选择嵌套严重的下拉元素
- 使用 javascript 通过 tag->id->element 获取嵌套元素
- 验证嵌套在ng中的输入元素repeat也用于页面加载,而不仅仅用于更改
- SVG:<使用>元素嵌套在g中时不起作用(带小提琴!
- 多元素嵌套列表的自定义排序
- 如何选择一个特定的元素嵌套表在html中使用jquery