In our last unit we previewed some new stuff - now it's time to learn it!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Document Object Model (DOM)¶
- We get access to an element object with the
- We modify the content with the
Getting an Element Object¶
<h2> element. Knowing what you know about HTML, how can uniquely identify the
<!--HTML--> <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h2>Hello, World!</h2> </body> </html>
That's right, an
<!--HTML--> <h2 id="greeting">Hello, World!</h2>
The .getElementById() Method¶
id value. If we are getting an element, which is data (an object), we need a variable to store it in.
getElementById()is a method of the
- It finds the element in the DOM with an
- Then, the element object is stored in the
id value is a string, so it must be enclosed in quotes.
1 2 3
Modifying the element content¶
Now that we have the element object, in this case a
<h2> object. We can modify it's content.
Right now the content of the
<h2> is "Hello, World!", let's change it!
headerTagis a variable holding the
- Using the
innerHTMLproperty of that object, we can change the content
The content of the
<h2> element changes in the HTML!
<!--HTML--> <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h2 id="greeting">This is new!</h2> </body> </html>
In the above example, we used the assignment operator
=. Remember, this erases and replaces. Therefore, the "Hello World!" text was erased and replaced with "This is new!".
But, what if we don't want to erase what is already there. What if we just want to add content. Well, we know of an operator that does that!
Now, the content was appended with "It's a great day."
<!--HTML--> <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h2 id="greeting">Hello, World! It's a great day.</h2> </body> </html>
Adding HTML Elements¶
Here's an unordered list with no list item tags:
<!--HTML--> <ul id="testUl"></ul>
Add a couple of
<li> tags to the list.
- Create a variable to hold the element object
- Get the
<ul>element with the
getElementById()method, using the
- Store the element object in the
- Put the first list item in the
<ul>object with the
- Add another list item to the
1 2 3 4 5 6 7 8 9 10
<!--HTML--> <ul id="testUl"> <li>first item</li> <li>second item</li> </ul>
A better way¶
innerHTML does cause the browser to refresh so you want to use it sparingly. The above code would be better like this.
- Create a variable to hold all the new HTML content.
- Use that variable to build up the content for the HTML page
- Use the
.innerHTMLproperty once, when you're ready to output to the page
- Lab01: Working with innerHTML