How to Add a Child Element to the DOM
A guide on how to dynamically create a new HTML element and add it as a child to an existing element in the DOM using TypeScript.
When I get search results back from a library, I need a way to show them on the page. I do this by creating new HTML elements for each result and adding them to a container in the DOM.
I start with an empty <div>
that will hold all the result items.
<div id="search-items"></div>
When I have the searcsh results, I loop through them, create a new <a>
tag for
each one, and add it to my search-items
div.
// First, I clear out any old results
searchItems.innerHTML = "";
searchResults.forEach((result) => {
// 1. I create a new <a> element in memory
const link = document.createElement("a");
// 2. Then, I set its properties
link.href = result.url;
link.className = "search-result-item"; // Use className to add classes
link.textContent = result.meta.title;
// 3. Finally, I add it to the parent div on the page
searchItems.appendChild(link);
});
First, I use document.createElement("a")
to create a new <a>
tag. This new
element exists, but it’s not on the page yet.
Next, I set all the properties I need on it, like href
for the link,
className
to add CSS classes, and textContent
for the visible text.
The last and most important step is searchItems.appendChild(link)
. This takes
the new <a>
tag I created and adds it as the last child inside my
search-items
div, which makes it show up on the page.
I also make sure to clear the container with searchItems.innerHTML = ""
before
adding new results. This stops the list from growing forever with old results
every time a new search is done.