开发者

document.setAttribute does not seem to work

开发者 https://www.devze.com 2023-02-19 07:49 出处:网络
I wrote a simple javascript function that creates a DOM object (in this case a tag ) and I call it in theof my html page and it doesn\'t seem to work. Any ideas?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消