构建一个JS函数来动态创建HTML元素并将它们嵌套在彼此内部

Building a JS Function to dynamically create HTML elements and nest them inside each other

本文关键字:元素 嵌套 内部 HTML 创建 一个 JS 动态 函数 构建      更新时间:2023-09-26

我创建了以下函数动态创建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是一个方法,而不是属性。