- Element: innerHTML property
- Value
- Exceptions
- Usage notes
- Reading the HTML contents of an element
- Replacing the contents of an element
- Operational details
- Appending HTML to an element
- HTML
- JavaScript
- Security considerations
- Examples
- JavaScript
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- CSS Before and CSS After – How to Use the Content Property
- Prerequisite
- Accepted Values
- String
- Advanced Quotes
- Images
- Outside of Pseudo Elements
- Conclusion
- Thanks for reading!
Element: innerHTML property
The Element property innerHTML gets or sets the HTML or XML markup contained within the element.
To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .
Value
A string containing the HTML serialization of the element’s descendants. Setting the value of innerHTML removes all of the element’s descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString.
Exceptions
Thrown if an attempt was made to set the value of innerHTML using a string which is not properly-formed HTML.
Thrown if an attempt was made to insert the HTML into a node whose parent is a Document .
Usage notes
The innerHTML property can be used to examine the current HTML source of the page, including any changes that have been made since the page was initially loaded.
Reading the HTML contents of an element
Reading innerHTML causes the user agent to serialize the HTML or XML fragment comprised of the element’s descendants. The resulting string is returned.
let contents = myElement.innerHTML;
This lets you look at the HTML markup of the element’s content nodes.
Note: The returned HTML or XML fragment is generated based on the current contents of the element, so the markup and formatting of the returned fragment is likely not to match the original page markup.
Replacing the contents of an element
Setting the value of innerHTML lets you easily replace the existing contents of an element with new content.
Note: This is a security risk if the string to be inserted might contain potentially malicious content. When inserting user-supplied data you should always consider using Element.setHTML() instead, in order to sanitize the content before it is inserted.
For example, you can erase the entire contents of a document by clearing the contents of the document’s body attribute:
This example fetches the document’s current HTML markup and replaces the »
.documentElement.innerHTML = ` $document.documentElement.innerHTML.replace( //g, "<", )> `;
Operational details
What exactly happens when you set value of innerHTML ? Doing so causes the user agent to follow these steps:
- The specified value is parsed as HTML or XML (based on the document type), resulting in a DocumentFragment object representing the new set of DOM nodes for the new elements.
- If the element whose contents are being replaced is a element, then the element’s content attribute is replaced with the new DocumentFragment created in step 1.
- For all other elements, the element’s contents are replaced with the nodes in the new DocumentFragment .
Appending HTML to an element
Setting the value of innerHTML lets you append new contents to the existing one of an element.
HTML
ul id="list"> li>a href="#">Item 1a>li> li>a href="#">Item 2a>li> li>a href="#">Item 3a>li> ul>
JavaScript
Please note that using innerHTML to append HTML elements (e.g. el.innerHTML += «link» ) will result in the removal of any previously set event listeners. That is, after you append any HTML element that way you won’t be able to listen to the previously set event listeners.
Security considerations
It is not uncommon to see innerHTML used to insert text into a web page. There is potential for this to become an attack vector on a site, creating a potential security risk.
let name = "John"; // assuming 'el' is an HTML DOM element el.innerHTML = name; // harmless in this case // … name = ""; el.innerHTML = name; // harmless in this case
Although this may look like a cross-site scripting attack, the result is harmless. HTML specifies that a tag inserted with innerHTML should not execute.
const name = ""; el.innerHTML = name; // shows the alert
For that reason, it is recommended that instead of innerHTML you use:
- Element.setHTML() to sanitize the text before it is inserted into the DOM.
- Node.textContent when inserting plain text, as this inserts it as raw text rather than parsing it as HTML.
Warning: If your project is one that will undergo any form of security review, using innerHTML most likely will result in your code being rejected. For example, if you use innerHTML in a browser extension and submit the extension to addons.mozilla.org, it may be rejected in the review process. Please see Safely inserting external content into a page for alternative methods.
Examples
This example uses innerHTML to create a mechanism for logging messages into a box on a web page.
JavaScript
function log(msg) const logElem = document.querySelector(".log"); const time = new Date(); const timeStr = time.toLocaleTimeString(); logElem.innerHTML += `$timeStr>: $msg>
`; > log("Logging mouse events inside this container…");
The log() function creates the log output by getting the current time from a Date object using toLocaleTimeString() , and building a string with the timestamp and the message text. Then the message is appended to the box with the class «log» .
We add a second method that logs information about MouseEvent based events (such as mousedown , click , and mouseenter ):
function logEvent(event) const msg = `Event $event.type> at $event.clientX>, $event.clientY> `; log(msg); >
Then we use this as the event handler for a number of mouse events on the box that contains our log:
const boxElem = document.querySelector(".box"); boxElem.addEventListener("mousedown", logEvent); boxElem.addEventListener("mouseup", logEvent); boxElem.addEventListener("click", logEvent); boxElem.addEventListener("mouseenter", logEvent); boxElem.addEventListener("mouseleave", logEvent);
HTML
The HTML is quite simple for our example.
div class="box"> div>strong>Log:strong>div> div class="log">div> div>
CSS
The following CSS styles our example content.
.box width: 600px; height: 300px; border: 1px solid black; padding: 2px 4px; overflow-y: scroll; overflow-x: auto; > .log margin-top: 8px; font-family: monospace; >
Result
The resulting content looks like this. You can see output into the log by moving the mouse in and out of the box, clicking in it, and so forth.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
- Node.textContent and HTMLElement.innerText
- Element.insertAdjacentHTML()
- Element.outerHTML
- Element.setHTML
- Parsing HTML or XML into a DOM tree: DOMParser
- Serializing a DOM tree into an XML string: XMLSerializer
Found a content problem with this page?
This page was last modified on Jul 7, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
CSS Before and CSS After – How to Use the Content Property
Jesse Hall
The content property in CSS defines the content of an element. You may have heard that this property only applies to the ::before and ::after pseudo-elements. In this article, we’ll explore various use cases for the content property, including outside of pseudo-elements.
Prerequisite
Since the majority of the use cases for the content property involve pseudo-elements, I would suggest that you be familiar with how the ::before and ::after pseudo-elements work. Here is a great article to get you up to speed:
Accepted Values
First, let’s take a look at all of the accepted values of the content property.
- normal : This is the default value. Computes to none when used with pseudo-elements.
- none : A pseudo-element will not be generated.
- : Sets the content to the string specified. This string can contain Unicode escape sequences. For example, the copyright symbol: \\000A9 .
- : Sets the content to an image or gradient using url() or linear-gradient() .
- open-quote | close-quote : Sets the content to the appropriate quote character referenced from the quotes property.
- no-open-quote | no-close-quote : Removes a quote from the selected element, but still increments or decrements the nesting level referenced from the quotes property.
- attr(*attribute*) : Sets the content as the string value of the selected elements selected attribute.
- counter() : Sets the content as the value of a counter , usually a number.
String
One of the most basic examples would be the use of adding string content before or after an element. In this example, we’ll add a link symbol before a link and add the URL for the link after it.
Notice the space after the Unicode character in the ::before pseudo-element and the before the first parenthesis in the ::after pseudo-element. This will create space between these and the parent element.
Alternatively, you could add padding or margin to the pseudo-elements to add separation.
Advanced Quotes
We can also specify where we do not want quotes. For example, you may be quoting someone who is quoting another person. So you would have quotes within quotes, which can get confusing to the reader.
In the CodePen below, we are using HTML tags, then specifying which tags should not display the quotes.
At first glance, you might think that we should just remove the tag where needed. But by specifying where a quote should not be still increments or decrements the nesting level referenced from the quotes property.
To explain this, we need to understand the quotes property. This is simply an «array» of characters that should be used when quoting. Here is an example:
These are sets of quotes. The first set will be used for the top level of quotes. The second set will be used for the first nested quote. And the third set will be used for the second nested quote. And so on, if there were more sets included.
Now that we understand the quotes property, I can explain how the no-open-quote and no-close-quote properties work.
For each level of quotes, we can assign different sets of characters to use for the quotes. By specifying where a quote should not be still increments or decrements the nesting level referenced from the quotes property.
Take a look at the example below. You will see that the second level of quotes is skipped.
You could use this to customize content within each list item that needs a corresponding number. Or you could use this to customize the list item itself. For instance, you could remove the default numbering and implement a custom-styled numbering system.
Images
Images and gradients can be used with the content property. This is fairly straight-forward. Here is an example that uses both:
For accessibility, there is also an option to add alternate text for the image. This feature is not fully supported though.
content: url(//unsplash.it/200/200) / "Alternative Text Here";
Outside of Pseudo Elements
That’s right! You can use the content property outside of the pseudo-elements ::before and ::after . Although, its use is limited and not fully compatible in all browsers.
The most compatible use case would be replacement of an element.
Conclusion
Most times you will see content: «» found in the ::before and ::after pseudo-elements. But the content property has many useful applications.
The best use in my opinion is to use it for updating bulk elements. If you want to add an icon before every link on your site, it would be much easier to add it through the content property than to add it to every element in the HTML document.
Thanks for reading!
Thank you for reading this article. Hopefully, it has helped you to better understand how the content property works in CSS.
I’m Jesse from Texas. Check out my other content and let me know how I can help you on your journey to becoming a web developer.