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.
source to share
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
source to share
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);
source to share
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);
source to share