2014-02-18 64 views
0

我是新来的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); 
+1

为什么你需要嵌套链接? – elclanrs

+1

“不工作”是什么意思? (无论如何,'getElementsByTagName'返回一个*集合*,而不是一个元素 - 所以至少最后一行将不起作用。) – user2864740

+1

另外'target'是一个NodeList。控制台说什么? – elclanrs

回答

0

变化target.appendChild(newLink);在代码target[0].appendChild(newLink);

“目标”是 数组 所有 链接 一个元素NodeList,所以要挑你需要说目标的第一个[0]

+0

您,先生,是一位学者和一位绅士!它的工作原理是:D – MatthewS

+0

* target *是一个(live)[NodeList](http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-536297177),而不是一个数组,参见[*文档界面的getElementsByTagName *](http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-A6C9094)方法。 – RobG