Labs ICT
Pro Login

DOM Updates

Injecting EJS-rendered content into the page.

innerHTML with EJS Output

The most straightforward way to update the DOM is to render an EJS template and assign it to innerHTML. It replaces everything inside the target element.


<script src="https://cdn.jsdelivr.net/npm/ejs/ejs.min.js"></script>

<div id="output"></div>

<script>
  var tpl = "<h2><%= title %></h2><p><%= body %></p>";
  var html = ejs.render(tpl, { title: "Notice", body: "Something changed." });
  document.getElementById("output").innerHTML = html;
</script>
    

This is quick and works well for replacing entire sections of a page with new content.

Creating Elements Dynamically

Sometimes you want to add new elements without replacing existing ones. Render EJS output and append it to the DOM.


<script src="https://cdn.jsdelivr.net/npm/ejs/ejs.min.js"></script>

<ul id="list"></ul>

<script>
  var items = ["Item 1", "Item 2", "Item 3"];
  var tpl = "<li><%= text %></li>";
  var list = document.getElementById("list");

  items.forEach(function(item) {
    var li = document.createElement("li");
    li.innerHTML = ejs.render(tpl, { text: item });
    list.appendChild(li);
  });
</script>
    

You create each element with createElement, then fill it with rendered EJS. This gives you precise control over where content goes.

Replacing Content Safely

When updating the DOM, you often need to preserve event listeners or state. Use targeted updates instead of replacing everything.


<script src="https://cdn.jsdelivr.net/npm/ejs/ejs.min.js"></script>

<div id="card">
  <h3 id="card-title"></h3>
  <p id="card-body"></p>
</div>

<script>
  function updateCard(data) {
    var titleTpl = "<%= title %>";
    var bodyTpl = "<%= body %>";
    document.getElementById("card-title").innerHTML = ejs.render(titleTpl, data);
    document.getElementById("card-body").innerHTML = ejs.render(bodyTpl, data);
  }

  updateCard({ title: "Updated!", body: "Only the text changed." });
</script>
    

By targeting specific elements, you avoid tearing down and rebuilding the entire component.

Animating Rendered Templates

You can add CSS transitions or animations to freshly rendered EJS content for a polished user experience.


<script src="https://cdn.jsdelivr.net/npm/ejs/ejs.min.js"></script>

<style>
  .fade-in { opacity: 0; transition: opacity 0.5s; }
  .fade-in.show { opacity: 1; }
</style>

<div id="target"></div>

<script>
  var tpl = "<div class='fade-in'><%= message %></div>";
  var html = ejs.render(tpl, { message: "Hello, world!" });
  var target = document.getElementById("target");
  target.innerHTML = html;

  requestAnimationFrame(function() {
    target.querySelector(".fade-in").classList.add("show");
  });
</script>
    

Render the element, insert it, then trigger the animation with a class change. It's a simple way to make content feel alive.

Try it Yourself →