You can change an element's attributes (style), insert HTML into the element, or insert/create new elements in specific places.
Changing an Element's Attributes
You can change attributes of specific elements. To change an element's attributes, you first get the element, set it as a variable, and then use the
setAttribute method to change its attributes. Here's an example:
setAttribute method has two values. You first list the name of the attribute you want to change, and then you list the value.
background-color become one word with camel casing:
To apply an inline style to an element, use the following format:
Changing the Contents of an Element
To change the actual contents of an element, you use the
You can see what the inner HTML is for an element by running this console.log message in Firebug:
The preceding statement allows you to view the inner HTML. To change the inner HTML, use a statement such as this:
Adding New Elements
You can also insert an entirely new element into the DOM. To insert a new element, follow these two steps:
- Create the element.
- Add the new element to the DOM
You create a new element by using the
createElement method with the Document object:
Once you create the element, you now need to append it somewhere. To append the new element, use the
There's another method for inserting a new element. Rather than creating new innerHTML to insert, you can insert a new text node by using the
This statement will append the newly created text node (
"Did you know?") on the
newSection paragraph element.