JavaScript-如何向DOM添加链接

JavaScript-如何向DOM添加链接,javascript,Javascript,我是JavaScript新手,所以这个问题对你们来说可能很简单: 我正在尝试向DOM添加一个额外的URL链接,但我当前的代码不起作用。在我看来,我的代码应该可以完美地工作,但代码本身必须有不同的想法 // Additional URL link that will go under the first one // Establish a connection in the DOM var target = document.getElementsByTagName("a"); // We n

我是JavaScript新手,所以这个问题对你们来说可能很简单:

我正在尝试向DOM添加一个额外的URL链接,但我当前的代码不起作用。在我看来,我的代码应该可以完美地工作,但代码本身必须有不同的想法

// 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);

更改
target.appendChild(newLink)
目标[0]。追加子项(新链接)


代码中的“target”是所有链接a元素的数组a,因此要选择第一个链接,您需要说target[0]

为什么需要嵌套链接?什么是“不起作用”呢?(无论如何,
getElementsByTagName
返回一个集合,而不是一个元素-因此至少最后一行不起作用。)另外,
target
是一个节点列表。控制台上说什么?是做家庭作业用的。我给我的教授发了电子邮件,她给了我一些建议;但是,代码仍然不起作用,任务今晚就要完成了:(当我说“不起作用”时,实际的URL链接和可点击文本没有出现。控制台说“UncaughtTypeError:Object”没有方法“appendChild”我确信这是显而易见的,但我已经引用了一个链接,以获得进入DOM的入口点。目标是一个(活动的),而不是一个数组。请参阅文档接口的方法。