I'm trying to get a grasp on html and javascript and wondering if there is a functional difference between using document.createElement(some_tag)
vs <some tag></some tag>
. I can see how using javascript's create element might make it easy to create the specific element over and over in different pages/sections of the website (instead of copying and pasting and making your code bulky). But is it bad practice/bad for memory or something to use create element.
For instance, consider the following code:
function createhtml() {
var li1 = document.createElement("li");
var text1 = document.createTextNode("First List Item");
li1.appendChild(text1);
var ul1 = document.createElement("ul");
ul1.appendChild(li1);
document.body.appendChild(ul1);
}
<body onload="createhtml()">
</body>
Is it better to do that, or simply:
<ul>
<li>First List Item </li>
</ul>
Or are they both exactly the same, and the second one is just easier/faster to type.
I've found that keeping things separated will save you a lot of frustration down the road. Defining the objects on your page should go in your HTML, styling and animating those elements should go in your CSS and making things do stuff should go in your javascript. Of course, this isn't a hard and fast rule but keeping things separated by intention makes it easier to read and easier to find what you're looking for. Additionally, in response to which method is faster, the pre-assembled HTML is going to load faster than trying to assemble it in js on the fly.
TLDR; create the elements in your HTML whenever possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With