将一个元素追加到另一个元素的子元素中

Appending an element inside the child of another element

本文关键字:元素 另一个 追加 一个      更新时间:2023-09-26

我正在尝试将链接("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);

首先,创建节点:

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

然后,使用 appendChild 追加子项:

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

或者,根据您的更新(删除其他元素),请使用replaceChild

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

你在那里!