The Best Way to Create HTML Elements with JavaScript?
Вставка
- Опубліковано 6 вер 2024
- In today's video I'll be showing you my favourite way to generate HTML elements using JavaScript.
This technique allows you to pass in an HTML string and receive an HTML element back, meaning you then have access to things such as class list, event listeners, text content etc.
For your reference, check this out:
developer.mozi...
🏫 My Udemy Courses - www.udemy.com/...
🎨 Download my VS Code theme - marketplace.vi...
💜 Join my Discord Server - / discord
🐦 Find me on Twitter - / dcodeyt
💸 Support me on Patreon - / dcode
📰 Follow me on DEV Community - dev.to/dcodeyt
📹 Join this channel to get access to perks - / @dcode-software
If this video helped you out and you'd like to see more, make sure to leave a like and subscribe to dcode!
#dcode #javascript
Another technique I also like to use is return document.createRange().createContextualFragment("...").firstElementChild;
I like using createContextualFragment instead of innerHTML because it's alot more faster and can run script tags.
Worth to mention, that using innerHTML is a security risk if the string to be inserted might contain potentially malicious content. When inserting user-supplied data you should always consider to sanitize the content before it is inserted.
I use it for elements that I know don't have user entered data because I've read it's more performant. Good point though
Then what to use man?
@@sujayxaradhyayeah, i also wanna know what to use instead
I believe they are saying I can use it, but you must check the data you inserting before you do so otherwise creates an exploit.
Не лучше ли использовать в отдельных файлах html с подключенным в них файлах сценариев и стилей, чтобы затем подключить их в директивой
is your name ACTUALLY dom?
Ja hy is Dom
@Panthon69 are you south african?😅
@@functionfofx prety obvs lmao
Very clear concepts. Thank you.
I have a single doubt regarding "template" parameter. I mean, what type of data si it treated like? as a string, as html tag? as a div using class="template"?.
Thank yo in advance. I hope you can respond
I literary was just looking for a video like this! That's why I'm subscribed to you!
Glad I could help!
Solid video. Thanks for that 👍 im new to web development in general. For me its kind of "not the best way" to generate an element by passing the whole html string. In my studies/tryouts i found that the document.createElement("ul") and then pass the attributes like innerhtml, class etc by just dotting the element was more "handsome". Am i missing something here?
Best regards
Another way is just to create template section with ID in your document and use that template in any place. For example dynamic created gallery.
The downside here is that it would require that the template existed in the DOM prior to the instantiation
@@allanmoreno6333Yes, but the idea is to minimize DOM operations in JS and raise execution speed. Also, it is smaller text/code. If the template is quite complex it will be less time consuming to operate with instead create it with each function call.
Anatoli hi! Can you provide some code snippet, please
Hi guys! I have simple question.... How often do u use js to create some html element as web dev or use mostly writing code in html to create elements? Thanks for respons
Which code font family use in this video
I'm gonna cry I was so stuck you helped me out
You're welcome! Glad I could help
2:45 is where I'm stuck when I put the html into the console and hit enter mylist shows up null
i can import html from another using async await fetch and use eval command
every time i code document.getelementbyId the console says document is not defined. how could i overcome this problem.
I've made a video that might contain the solution to your problem:
ua-cam.com/video/d14vAVDCxEg/v-deo.html
@@dcode-software thanks for the response
Is this meant to turn plain text of a website into interactive text or objects? Aside from making buttons in HTML, it seems to be just text until you add JS to interact with the site?
Is using innerHTML safe for parsing?
Very cool. Thank you dcode.
You're welcome!
I kinda got lost at the very end. How do I put the list (button in my case) in the place I want? I see "document.body.appendChild(myList)" puts it in the body but how would i put it in a div with an id
"document.body" select the body. You need to select your div : “document.querySelector(‘#ID_NAME’)” the # is needed to say that what you search is an ID.
very good technique!!!
If I create input element using javascript, how to get the value the user will put inside?
input.value
As always very very nice content and exactly on point!
Glad you enjoyed it
Thanks for this great tutorial. However, I did exactly like you but it didn't work! I have a script tag and within that tag I want to check a condition and if it's True I want to display an HTML form but for some reason it's not working with me!! Any idea how to do that please
It would help me a lot to finish my project
the idea is to allow users to upload file only after payment is Success! I can rediret to a page for uploading file but this means anyone can go to that page and upload the file without payment! I hope you have a soulution for this issue
this only works if the html string argument has a single root node. if it’s a fragment with multiple root siblings, you’ll only get the first one back
Is it ok if I call you Document Object Model?
Yes
Eesh, setting up a bad example with your script element without "use strict" or type=module.
great ! thank you well done
thanks !!!!!
love it, first too
🎉
Thank you.
Brilliant 👌
You're welcome
❤️❤️❤️❤️❤️
Wow, don't do this.
How's any Englishman, on this taxan - ught? NTT? ETT= you - N=not. Tm= This maneuvifsz. Movements - moles?