javascript item.appendChild 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29762060/
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-10-28 11:01:46  来源:igfitidea点击:

item.appendChild is not a function

javascripthtmlcssdom

提问by Bruno Tavares

I know this is a very common error but I have read and read and can't figure it out why. It's probably something very easy but I can't solve it by myself.

我知道这是一个非常常见的错误,但我已经阅读并阅读,但无法弄清楚原因。这可能很容易,但我无法自己解决。

var item = document.createElement("div").className = "item";
var img = document.createElement("img").src = imgpath + $(this).attr("href");;
item.appendChild(img);

Any help is appreciated!

任何帮助表示赞赏!

EDIT:

编辑:

var item = document.createElement("div");
item.className = "item";
var img = document.createElement("img");
img.src = imgpath + $(this).attr("href");
item.append(img);

This throws the same error.

这会引发相同的错误。

采纳答案by Arun P Johny

In your case you are creating a div and assigns it a class name, and the same value(class name) is assigned to the itemvariable. So it is a string value which does not have the appendChildmethod.

在您的情况下,您正在创建一个 div 并为其分配一个类名,并将相同的值(类名)分配给该item变量。所以它是一个没有appendChild方法的字符串值。

var item = document.createElement("div");
item.className = "item";
var img = document.createElement("img");
img.src = imgpath + $(this).attr("href");;
item.appendChild(img);

The same concept applies to imgalso

同样的概念img也适用于

回答by Mritunjay

Problem is here

问题在这里

document.createElement("div").className = "item"

it will return a stringwhich won't have a method called appendChildon it. You don't have any reference to the created div.

它将返回一个string不会调用appendChild它的方法。您没有任何对创建的div.

You should be doing like this

你应该这样做

var item = document.createElement("div");
item.className = "item";

var img = document.createElement("img");
img.src = imgpath + $(this).attr("href");
item.appendChild(img);

回答by epascarello

Because item is the string "item", not an element. You need to break it up.

因为 item 是字符串“item”,而不是元素。你需要打破它。

var item = document.createElement("div");
item.className = "item";

Same thing needs to happen with the image.

图像也需要发生同样的事情。

回答by S McCrohan

document.createElement("div").className = "item";returns a string, not a DOM node, so it knows nothing about .appendChild(). Try this instead:

document.createElement("div").className = "item";返回一个字符串,而不是一个 DOM 节点,所以它对.appendChild(). 试试这个:

var item = document.createElement("div");
item.className = "item";
var img = document.createElement("img");
img.src = imgpath + $(this).attr("href");
item.appendChild(img);