我是新来的JavaScript,所以这个问题可能会很容易为你们:JavaScript的 - 如何添加链接到DOM
我想一个额外的URL链接添加到DOM,但我目前的代码不起作用。在我看来,我的代码应该完美工作,但代码本身必须另有其他。
// Additional URL link that will go under the first one
// Establish a connection in the DOM
var target = document.getElementsByTagName("a");
// We need to create new element
var newLink = document.createElement("a");
// We have the new "a" tag created, but we also have to add some things to it
newLink.setAttribute("href", "http://www.ign.com/");
// Now we need to add some text for the end user to click for the new "a" element
newLink.appendChild(document.createTextNode("Click Me!"));
// Finally, add the new element and we're golden
target.appendChild(newLink);
为什么你需要嵌套链接? – elclanrs
“不工作”是什么意思? (无论如何,'getElementsByTagName'返回一个*集合*,而不是一个元素 - 所以至少最后一行将不起作用。) – user2864740
另外'target'是一个NodeList。控制台说什么? – elclanrs