Javascript 未捕获的类型错误:无法在“节点”上执行“appendChild”:参数 1 的类型不是“节点”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32447388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 08:03:52  来源:igfitidea点击:

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

javascriptjquery

提问by Cecil Rodriguez

var line = "<p><strong>" + name + ": </strong>" + message.field_message_body.und[0].value + "</p>";
console.log(line);
console.log(document.getElementById("messages"));

document.getElementById("messages").appendChild(line);

messages exists and it returns

消息存在并返回

<div id=messages"></div>

<div id=messages"></div>

Nothing appears to be empty, so I'm not sure why this is being thrown.

似乎没有什么是空的,所以我不确定为什么会抛出这个问题。

Does anyone have any idea why it might be throwing this error?

有谁知道为什么它可能会抛出这个错误?

回答by RK.

The linevariable you're passing isn't a Node, it's a String. Try first using

line您传递的变量不是Node,而是String。首先尝试使用

var line = document.createElement("p");
line.innerHTML = "<strong>" + name + ": </strong>" + message.field_message_body.und[0].value;
document.getElementById("messages").appendChild(line);

回答by Beroza Paul

How about this:

这个怎么样:

var line = "<p><strong>" + name + ": </strong>" + message.field_message_body.und[0].value + "</p>";
var msgHTML = document.getElementById("messages").innerHTML;
document.getElementById("messages").innerHTML = msgHTML + line;