Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

item.appendChild is not a function

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.

like image 605
Bruno Tavares Avatar asked Jul 23 '26 17:07

Bruno Tavares


2 Answers

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

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 img also

like image 193
Arun P Johny Avatar answered Jul 26 '26 07:07

Arun P Johny


Problem is here

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

it will return a string which won't have a method called appendChild on it. You don't have any reference to the created 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);
like image 45
Mritunjay Avatar answered Jul 26 '26 06:07

Mritunjay