如何将div插入到javascript中创建的另一个div中

时间:2014-04-03 15:39:11

标签: javascript jquery html

所以我试图将一个div插入另一个用Javascript创建的div 我有以下代码,

// Assign tool attributes to Javascript Variables
    var tool_name = String(tool['tool_name']);
    tool_name = tool_name.replace(/'/g, '');
    var tool_inventory_number = String(tool['tool_inventory_number']);
    tool_inventory_number = tool_inventory_number.replace(/'/g, '');
    var tool_recnum = String(tool['tool_recnum']);
    tool_recnum = tool_recnum.replace(/'/g, '');

// Create the divs for the search results
    var toolDiv = document.createElement("div");
    var toolDivPicture = document.createElement("div");
    //todo: Insert picture into this toolDivPicture div
    var toolDivDescription = document.createElement("div");
    toolDivDescription = toolDivDescription.innerHTML + "<h2>" + tool_name + "</h3>" + "    <br>" + "Inventory Number: " + tool_inventory_number;

// Assign class to search result toolDiv and add content to it.
    toolDiv.className = "toolDiv";
    toolDiv.appendChild(toolDivDescription);

我一直收到以下错误,

Uncaught NotFoundError:无法在'Node'上执行'appendChild':新的子元素为null。

这可能是因为我必须通过id来引用子div吗?我真的只想让javascript创建一个包含两个其他div的div,然后将其插入到页面中。任何帮助/建议表示赞赏!

2 个答案:

答案 0 :(得分:1)

由于您使用jQuery标记标记了问题,我假设您已加载jQuery库:

// Create the divs for the search results
var toolDiv = $("<div/>");
var toolDivPicture = $("<div/>");
var toolDivDescription = $("<div/>");
toolDivDescription.html("<h2>" + tool_name + "</h3>" + "    <br>" + "Inventory Number: " + tool_inventory_number);

// Assign class to search result toolDiv and add content to it.
toolDiv.addClass("toolDiv");
toolDiv.append(toolDivDescription);

请注意,您开始使用h2但结束了h3。

jsFiddle

答案 1 :(得分:0)

试试这个:

在onload函数中包装JavaScript。首先添加:

<body onload="loadJS()">

然后将你的javascript放在加载函数中,所以:

function loadJS() {
    // Assign tool attributes to Javascript Variables
    var tool_name = String(tool['tool_name']);
    tool_name = tool_name.replace(/'/g, '');
    var tool_inventory_number = String(tool['tool_inventory_number']);
    tool_inventory_number = tool_inventory_number.replace(/'/g, '');
    var tool_recnum = String(tool['tool_recnum']);
    tool_recnum = tool_recnum.replace(/'/g, '');

// Create the divs for the search results
    var toolDiv = document.createElement("div");
    var toolDivPicture = document.createElement("div");
    //todo: Insert picture into this toolDivPicture div
    var toolDivDescription = document.createElement("div");
    toolDivDescription = toolDivDescription.innerHTML + "<h2>" + tool_name + "</h3>" + "    <br>" + "Inventory Number: " + tool_inventory_number;

// Assign class to search result toolDiv and add content to it.
    toolDiv.className = "toolDiv";
    toolDiv.appendChild(toolDivDescription);
}