Submodule 14.2: DOM methods/properties and DOM Recursion

Creating and inserting DOM elements

Here we will see how we can use some of the DOM methods and properties to create a new Node and then attach it to the appropriate place. 

DOM provides us with 3 different ways of creating new Nodes:

  1. document.createElement()
  2. document.createTextNode()
  3. document.createAttribute()

In order to attach the Node created on the appropriate place or remove an existing one, we can use:

  • element.appendChild()
  • element.insertBefore()
  • element.removeChild()
  • element.replaceChild()
  • element.setAttributeNode()

Let's see an example where we use what we learned above to add a list item in the next HTML page.

Code:

Exercise

    1. Open your editor, create a new file and save it as exersice14.2.2.html in the folder "yourNameWEB2JS".
    2. Copy the code below and paste it in the new file.
    3. Open the file in your browser to see the results.
    4. Uncomment the script tag to see the results.
    5. Uncomment the style tag to see the results.
    6.  Modify the above code to add an h3 tag after the h1 tag.

Answer: