在另一个元素的子元素中添加元素

时间:2013-09-24 11:32:44

标签: javascript append appendchild

我正在尝试将链接(“a”标记)附加到“topBar”元素的子元素。 这是我到目前为止所得到的:

document.getElementById('topBar').innerHTML += '<a href="http://orteil.dashnet.org/experiments/cookie/" target="blank">Cookie Clicker Classic</a>';

这会将“topBar”元素中的链接作为新子元素,但我希望它位于“topBar”元素的现有子元素中。我该怎么做呢?这个孩子只是在一个div标签内,它没有id ...我已经对.appendChild进行了一些研究,但我没有找到任何相关的帮助,因此我在这里问这个问题......

我非常感谢任何想法甚至是要发布的解决方案。 谢谢, 丹尼尔

编辑:topBar只有一个孩子,它是无名的

另外,我做错了吗?

setTimeout(doSomething, 1000);
function doSomething() {
var element =  document.getElementById('particles');
if (typeof(element) != 'undefined' && element != null)
{
var newLink = document.createElement('a');
newLink.setAttribute('href', 'http://orteil.dashnet.org/experiments/cookie/');
newLink.target = 'blank';
document.getElementById('topBar').appendChild(newLink);
var del = document.getElementById('links')
del.parentNode.removeChild(del);
return;
} else {
setTimeout(doSomething, 1000);
}
}
编辑:我已经完成了!感谢大家的帮助,特别是Elias Van Ootegem。这是我用过的:

var link=document.createElement('a');
link.setAttribute('href', 'http://orteil.dashnet.org/experiments/cookie/');
link.target = 'blank';
link.appendChild(
document.createTextNode('Cookie Clicker Classic')
);
var add = document.getElementsByTagName('div')[1]; //this picked the second div tag in the whole document
if(add.lastChild) add.insertBefore(link,add.lastChild); //appending it to the end of the child
else add.prependChild(link);

1 个答案:

答案 0 :(得分:0)

首先,创建节点:

var newLink = document.createElement('a');
//set attributes
newLink.setAttribute('href', 'http://orteil.dashnet.org/experiments/cookie/');
newLink.target = 'blank';//preferred way is using setAttribute, though
//add inner text to link:
newLink.appendChild(
    document.createTextNode('Cookie Clicker Classic')//standard way, not innerHTML
);

然后,追加孩子,using appendChild

document.getElementById('topBar').appendChild(newLink);

或者,鉴于您的更新(删除其他元素),use replaceChild

document.getElementById('topBar').replaceChild(
    newLink,//new
    document.getElementById('links')//old, will be removed
);

你在那儿!

相关问题