JavaScript: Insertion of Elements
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:
The setAttribute
method has two values. You first list the name of the attribute you want to change, and then you list the value.
Applying Styles
You can also apply styles directly to elements. However, because JavaScript doesn't use hyphens or underscores, the CSS style names that are usually hyphenated (like background-color
become one word with camel casing: backgroundColor
.
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 innerHTML
method.
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 appendChild
method:
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 createTextNode
method.
This statement will append the newly created text node ("Did you know?"
) on the newSection
paragraph element.
About Tom Johnson
I'm an API technical writer based in the Seattle area. On this blog, I write about topics related to technical writing and communication — such as software documentation, API documentation, AI, information architecture, content strategy, writing processes, plain language, tech comm careers, and more. Check out my API documentation course if you're looking for more info about documenting APIs. Or see my posts on AI and AI course section for more on the latest in AI and tech comm.
If you're a technical writer and want to keep on top of the latest trends in the tech comm, 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.