Item.appendChild is not a function

I know this is a very common mistake, but I have read and read and cannot figure out why. This is probably something very simple, but I cannot solve this on my own.

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.

+3


source to share


4 answers


In your case, you create a div and give it a class name and one value (class name) is assigned to a variable item

. So it is a string value that has no method 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 applies to img

also

+2


source


The problem is here

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

      

it will return string

which does not have a named method appendChild

. You have no link to the created one div

.



You should do like this:

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

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

      

0


source


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

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

      

The same thing happens with the image.

0


source


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

returns a string, not a DOM node, so doesn't know anything about .appendChild()

. Try this instead:

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

      

0


source







All Articles