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()
.
This example uses innerHTML
to create a mechanism for logging messages into a box on a web page.
function log(msg) {
const logElem = document.querySelector(".log");
const time = new Date();
const timeStr = time.toLocaleTimeString();
logElem.innerHTML += `${timeStr}: ${msg}<br/>`;
}
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 <strong>${event.type}</strong> at <em>${event.clientX}, ${event.clientY}</em>`;
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);
The HTML is quite simple for our example.
<div class="box">
<div>
<strong>Log:</strong>
</div>
<div class="log">
</div>
</div>
The <div>
with the class "box"
is just a container for layout purposes, presenting the contents with a box around it. The <div>
whose class is "log"
is the container for the log text itself.
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;
}