I’m working on a project with vanilla JavaScript and am wondering about the best way to dynamically create and manage DOM elements.
I know that in libraries like React, JSX is transformed into React.createElement calls behind the scenes, which generates elements using something like this:
React.createElement("div", { className: "my-class" }, "Hello World")
In vanilla JavaScript, I could write a similar function to create DOM elements programmatically. However, I’m wondering why I should bother doing this when I can just use innerHTML or insertAdjacentHTML with template literals for a much simpler approach.
For example:
document.body.innerHTML =
Hello World;
What are the advantages of using a createElement-like function over innerHTML or insertAdjacentHTML for DOM manipulation? Is there a performance benefit, security reason, or best practice for larger applications that I should be aware of?