I wrote a simple javascript function that creates a DOM object (in this case a tag ) and I call it in the of my html page and it doesn't seem to work. Any ideas?
function create_link() {
var link = document.createElement("a");
link.setAttribute('href', 'the_link.html');
link.setAttribute('name', 'click on link');
document.childNodes[0].childNo开发者_如何转开发des[1].appendChild(link);
}
The createElement and setAttribute calls are fine, are you sure document.childNodes[0].childNodes[1]
is defined?
To test, you can do: document.body.appendChild(link);
, which should work.
The problem is likely with document.childNodes[0].childNodes[1]
. It's suggested that you use document.getElementById(id)
instead, especially since this is more resistant to changes in your HTML structure that may later be made.
In general, avoid using childNodes
to navigate to specific parts of the DOM.
精彩评论