vanilla js and Dom manipulation, which way is the “preferred” way of writing this?

Sorry in advance I’m typing this on s phone whilst I eat lunch 😂 I noticed vite has everything inside a querySelector.innerHTML and inside that you have your html tags and even classes/ids, but is this the correct way of doing it? The alternative would obviously be to create the html tag using Dom, then add an Id/class using Dom and access it from there.. Basically I’m trying to build an entire page by creating the content in the Dom and this is my first hurdle. My second hurdle being how am I supposed to position and style it all if it’s effectively going to be just a block of js code creating everything, so there’s no static html positioning (I may br overthinking this as I haven’t used Dom in a few months)
5 Replies
13eck
13eck2y ago
To answer your second question first: CSS is dynamic! As long as the element you’re adding has a class/id/other selector that’s in your linked CSS file it’ll work the way you expect. To answer your first question: I prefer createElement() and append(), especially for more complex HTML. The longer/more complex the string the harder the browser has to work to turn a string into DOM nodes. It also has the benefit that making changes easier! Instead of having to find the string-part that has the element you just swap out the code that creates the element that needs changing.
CDL
CDLOP2y ago
That definitely makes more sense, thanks Beck 🙂 Just to make sure I worded myself properly by the innerHTML part I meant
document.querySelect("#contact").innerHTML = "
<div id="contact">
<p>Some random info goes here</p>
</div>
document.querySelect("#contact").innerHTML = "
<div id="contact">
<p>Some random info goes here</p>
</div>
Jochem
Jochem2y ago
keep in mind that innerHTML will parse your html and run any script tags it finds, or load any assets referenced by replaced elements, so it's an XSS risk if you're not 100% in control of the content so never use it if you're representing user submitted content (or really anything you didn't personally type into your source code) without being sure you sanitized it properly
13eck
13eck2y ago
I was just going to say, another benefit of creating DOM nodes and using .innerText is that it’s safe from what Jochem mentioned :p
CDL
CDLOP2y ago
That makes sense and I've heard of it previously, thanks both 🙂 I'll work on appending
Want results from more Discord servers?
Add your server