Search code examples
javascriptappendappendchild

Appending an element inside the child of another element


I am trying to append a link ("a" tag) to a child of the "topBar" element. Here is what i've got so far:

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

This puts the link inside the "topBar" element as a new child, but I want it inside the existing child of the "topBar" element. How do I do this? The child is just within a div tag, it has no id... I have done some reasearch on .appendChild but I haven't found any related help, thus why I am asking here...

I would be very appreciative for any ideas or even a solution to be posted. Thanks, Daniel

EDIT: topBar has only one child, it is nameless

also, am I doing something wrong with this?

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

EDIT: I have finished! Thanks to everyone for their help, especially Elias Van Ootegem. This is what I used:

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

Solution

  • First, create the node:

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

    Then, append the child, using appendChild:

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

    Or, given your update (your deleting some other element), use replaceChild:

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

    And you're there!