DOM Manipulation
Let's try a quick example. Type the following into your browser's console:
document.getElementById('dom-manipulation').innerText = 'it\'s happening!';
Now refresh your page.
What happened here? The DOM document object represents our webpage. If we want to access or modify anything on the webpage, we do so through the document object.
The getElementById() method takes in a string as a parameter. It searches for and returns the element whose id matches the string parameter.
The innerText property is exactly that: the inner text of the HTML element. It can be modified.
There are numerous ways to access and modify webpages. Study and play with the properties and methods of the document object.
What other methods and properties can we use to manipulate the DOM?
Classwork
- Use the console, document and getElementById() to change the color of the element with the id document-object-model to any color besides black.
- Use the console, document and getElementById() to change the background color of the element with the id document-object-model to any color besides black.
- Change the font size of the elements with the class name normal to 16px. This one's a bit tougher. Make sure you understand the data structure your chosen method returns.
Note: These exercises require going into the DOM documentation as some necessary methods and properties were not described on this page.
Class Exercise
Setup
- Create a new Thimble project or a new folder on your local machine (using your local machine is better practice for real-world projects).
- Create an index.html file with the standard HTML skeleton.
- Create an app.js file in the same folder.
- Add a
scripttag to the line before the closingbodytag in index.html and link the app.js file using thesrcattribute - Open index.html. Nothing should show.
Exercise
The following exercise must be done using 100% DOM manipulation. Do not modify index.html.
- Create a new
divelement (it may help to save the element to a variable). - Add a main-div
idto your div element (you can use thesetAttributemethod). - Append the new
divelement to the document.body. - Create a new
buttonelement. - Add some text to your button. The text can say whatever you want.
- Append the button to main-div.
- Create another
buttonelement. - Add some text to your new button. The text should be different than the first button.
- Append the second button to the main-div. Reload
index.htmland you should see your two buttons. - Add the class btn to both of your buttons.
- Create an
ul(unordered list) element. - Append the
ulelement to the main-div. - Create three separate
li(list) items. - Append the
liitems to theul. - Add the class list-item to each of the
lielements. - Add the
idmain-list to theul.
Save this as you will continue to work on this in the next lesson.