Manipulating the DOM with javascript – part 3 of 4

In my last post, we explored the appendChild and insertBefore functions. As I explained, those are two of the three main functions you can use to add a new element into your HTML page. In this post, we will explore the replaceChild and removeChild functions.

replaceChild

The next function is the replaceChild function. Once again, it does exactly what it says. This will remove one element in the DOM and replace it with your new element. Using the examples from the last post, assuming that we assigned an ID of “img3” to our third image, we could use this function to remove img3 and replace it with “myimg”. The code for that would look like:

mydiv.replaceChild(myimg,document.getElementById('img3'));

The outline of our DOM would now look like:

  1. div (id=mydiv)
    1. img1
    2. img2
    3. myimg

removeChild

I’ve shown you the three basic ways to add elements to your HTML page, but I haven’t yet shown you how to get rid of elements that you no longer want. That’s where the removeChild function comes in. As you may have guessed from the name, this is another function that requires you to have a reference to the parent element. In the examples we’ve already used, our parent element is stored in the javascript variable “mydiv”, so we will continue to use that. Now, let’s say that we simply want to remove “img3”, rather than replacing it with “myimg”. We would do so by using the following code:

mydiv.removeChild(document.getElementById('img3');

In this case, the outline of our DOM would look something like the following.

  1. div (id=mydiv)
    1. img1
    2. img2

Another way of doing this would be to use the “parentNode” reference. Let’s say that we want to remove “mydiv” altogether, rather than just removing an element from inside of it. To do that, we would use the following code:

mydiv.parentNode.removeChild(mydiv);

The code above will remove the div that we’ve referenced as “mydiv”, along with all of its child elements.

In our next installment, we will explore how to add text to your elements, and will then put all of it together to show you a real world example.

One Response