Lesson 22: Dynamically Creating HTML Elements

This lesson is short and sweet, but what you learn is very powerful. Enjoy how quick this lesson goes because the next lesson will be a bear.

1. Create a wall class to use on all walls that will be added to the gameWindow.

You are probably thinking that you should add a wall directly into our HTML with something like
<div id="wall_1" class="wall"></div>
and then add a style for #wall_1 to size and position the wall. Not a bad idea... but it is time you learn how to create Elements dynamically with JavaScript.

2. Declare wall_1 as a global variable that will be set equal to the wall_1 element.

3. There is no such element in your HTML yet, so using getElementById() does not make sense. Instead, create a new element using the createElement() function. You can use the setAttribute() function to give the element an id, or to set any attribute of the element. Use className to give the element a class of wall and give the wall a size and location using the style object and relevant CSS properties. Finally, use the appendChild() function to add wall_1 to the gameWindow.

Note that there is a child/parent relationship between HTML elements. For instance, pacman is a child of gameWindow and gameWindow is a parent of pacman.

The wall should appear when the page is loaded. However, pacman can currently move behind the wall. Changing the z-index of elements so that the walls are behind pacman would bring pacman in front of the wall but would not stop him from running through the wall. You will solve this problem by the end of the lesson.


Test Yourself!

1. What JavaScript function can be used to dynamically create a new IMG element?
generateImg()
createImg()
generateElement('IMG')
createElement('IMG')
2. What JavaScript function can be used to add a dynamically created HTML Element to another HTML Element?
addChild()
appendChild()
addElement()
appendElement()
3. If boss is equal to an IMG element, what JavaScript command would be used to set the src of the element to 'myBoss.png'?
boss.setAttribute('src', 'myBoss.png');
boss.setAttribute('myBoss.png');
boss.setAttribute('myBoss.png', 'src');
boss.setAttribute('src');