如何使用javascript添加<a>标签和href

Sal*_*man 0 javascript

谁能告诉我如何<a>使用JavaScript在其中添加标签和href?

我在用:

document.createElement('a').setAttribute('href', '#');
Run Code Online (Sandbox Code Playgroud)

但它似乎没有用.

Nin*_*olz 8

您创建一个节点,但不将该节点分配给浏览器中的元素.

var a = document.createElement('a'); // generate node

a.setAttribute('href', '#');         // set attribute
a.textContent = 'foo';               // assign some text
// or use
// a.innerHTML = 'foo';
document.body.appendChild(a);        // use the node
Run Code Online (Sandbox Code Playgroud)