11

Possible Duplicate:
javascript appendChild doesn't work

The error occurs on the last line of this snippet:

 var anchor = "<a id=\"hostname\" href=\"" + destination + "\"> "+ imagename + "</a>";
 var specialdiv = document.getElementById("specialdiv");
 console.log("div: " + specialdiv);
 specialdiv.appendChild(anchor);

There's really nothing else going on... I verified that specialdiv isn't null or something like that. Can anyone explain why I'm getting this error on that line?

4

2 回答 2

15

不要传递字符串,而是传递元素

var link = document.createElement('a');
link.innerHTML = imagename;
link.id = "hostname";
link.href = destination;

var specialdiv = document.getElementById("specialdiv");
specialdiv.appendChild(link);
于 2012-07-24T22:50:43.783 回答
3

您收到该错误是因为appendChild需要 DOM 元素,而不是字符串。在使用appendChild.

var anchor = document.createElement('a');
anchor.id = "hostname";
anchor.href = destination;
anchor.innerHTML = imagename;

var specialdiv = document.getElementById("specialdiv");
specialdiv.appendChild(anchor);
于 2012-07-24T22:48:46.153 回答