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.
About Tom Johnson
I'm a technical writer / API doc specialist based in the Seattle area. In this blog, I write about topics related to technical writing and communication — such as software documentation, API documentation, visual communication, information architecture, writing techniques, plain language, tech comm careers, and more. Check out my API documentation if you're looking for more info about that. If you're a technical writer and want to keep on top of the latest trends in the field, be sure to subscribe to email updates below. You can also learn more about me or contact me. Finally, note that the opinions I express on my blog are my own points of view, not that of my employer.