0
Best or correct way to create and use DOM elements?
func makeE(){ x = document.crea...(âdivâ) x = className = âxyzâ; x.innerHTML = ` <p> blabla </p> <button> click me </button> `; document.body.appendChild(x) } Itâs easier to just do x.innerHTML = â<<elements>>â, than creating every child element. But when I try to get elements from the makeE function, it seems like the more elements I have inside x.innerHTML the more it doesnât work. (I get null or undefined) Is there a better way to createElements, & get elements and use in other functions?
8 Answers
+ 3
It should work, disregard how many html elements you set on innerHTML, if it doesn't work, there might be html syntax error on the assigned string.
Remember to use template literals which is enclosed by the backtick (` `) character, instead of double "..." or single quotes '...' to avoid errors.
+ 3
Ginfio heres another way to do it using cloneNode(), this may be somewhat more manageable
https://code.sololearn.com/WKDZnQt6JXsP/?ref=app
+ 2
Ginfio the other alternative is node creation/insertion...
I agree with CalviŐČ (and that's what I was meaning in my previous post): "It should work, disregard how many html elements you set on innerHTML, if it doesn't work, there might be html syntax error on the assigned string."
Giorgos Dim what is exactly the benefit to use cloneNode instead of createElement?... and if you want to use html templates, why not looking at <template> element ;) ?
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template
https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots
+ 1
the problem by building html string is that's error prone and hardest to debug ^^
handling elements/nodes creation and insertion in DOM tree could seems to require more works/code, but that's almost anecdotic, and less error prone.
hiwever I guess that's notmal to be more attracted by innerHTML, but I would advise to not close the door to the other alternative and progressively trying to increase part done with it (reserving innerHTML to small content, and using textContent as much as possible) ;)
+ 1
template is not only more semantically correct, but provide a way to include hidden content inside of the page source code...
I don't really like w3s... they have so outdated informations in their site ^^ anyway, if that fits to you, well done!
0
visph
what would be the other alternatives?
0
visph Thank, i didn't know about template tag. While normal div will also work the template tag is more semantically correct. I have also updated my code example to use template and a button.
As for your question, using cloneNode lets you write the html structure using html instead of JS commands which is easier imo
Also this tutorial on template tag is worth checking out:
https://www.w3schools.com/tags/tag_template.asp
0
Hello