The Best Way to Create HTML Elements with JavaScript?

Sdílet
Vložit
  • čas přidán 28. 03. 2022
  • 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.mozilla.org/en-US/d...
    🏫 My Udemy Courses - www.udemy.com/user/domenic-co...
    🎨 Download my VS Code theme - marketplace.visualstudio.com/...
    💜 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

Komentáře • 48

  • @user-rz4gs1qm6n
    @user-rz4gs1qm6n Před 2 lety +16

    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.

  • @user-fu8pd4cf6v
    @user-fu8pd4cf6v Před rokem +19

    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.

    • @miscany
      @miscany Před 8 měsíci

      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

    • @sujayxaradhya
      @sujayxaradhya Před 5 měsíci +1

      Then what to use man?

    •  Před 5 měsíci +1

      @@sujayxaradhyayeah, i also wanna know what to use instead

    • @bigfrostishere
      @bigfrostishere Před 2 měsíci

      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.

  • @sfmg
    @sfmg Před 2 lety +2

    I literary was just looking for a video like this! That's why I'm subscribed to you!

  • @teterposh7042
    @teterposh7042 Před 2 lety +3

    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

  • @JeanBotan
    @JeanBotan Před 6 měsíci +2

    Не лучше ли использовать в отдельных файлах html с подключенным в них файлах сценариев и стилей, чтобы затем подключить их в директивой

  • @GetShwiftyInHere
    @GetShwiftyInHere Před 8 měsíci

    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?

  • @danielsladecek8258
    @danielsladecek8258 Před 9 měsíci +1

    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

  • @DoubleNation
    @DoubleNation Před 2 lety +1

    As always very very nice content and exactly on point!

  • @aer0449
    @aer0449 Před rokem +1

    I'm gonna cry I was so stuck you helped me out

  • @elyasmohammadi3163
    @elyasmohammadi3163 Před 2 lety +1

    very good technique!!!

  • @rajankhunt7002
    @rajankhunt7002 Před rokem +1

    Which code font family use in this video

  • @gensys244
    @gensys244 Před 2 lety

    great ! thank you well done

  • @hericklenin
    @hericklenin Před 2 lety +1

    Very cool. Thank you dcode.

  • @georegio
    @georegio Před rokem

    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

    • @mandresy5750
      @mandresy5750 Před rokem

      "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.

  • @clashoffans496
    @clashoffans496 Před rokem +1

    Is using innerHTML safe for parsing?

  • @apgeorgiev
    @apgeorgiev Před 2 lety +4

    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.

    • @allanmoreno6333
      @allanmoreno6333 Před 2 lety

      The downside here is that it would require that the template existed in the DOM prior to the instantiation

    • @apgeorgiev
      @apgeorgiev Před rokem

      @@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.

    • @Hacking-NASSA-with-HTML
      @Hacking-NASSA-with-HTML Před rokem

      Anatoli hi! Can you provide some code snippet, please

  • @Hustlalyfe44
    @Hustlalyfe44 Před 6 měsíci

    2:45 is where I'm stuck when I put the html into the console and hit enter mylist shows up null

  • @lonewolfcoding5208
    @lonewolfcoding5208 Před rokem

    i can import html from another using async await fetch and use eval command

  • @isamal-abbasi2392
    @isamal-abbasi2392 Před rokem

    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

    • @isamal-abbasi2392
      @isamal-abbasi2392 Před rokem

      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

  • @rmlacana581
    @rmlacana581 Před 2 lety

    If I create input element using javascript, how to get the value the user will put inside?

  • @jasinAmsterdam1976
    @jasinAmsterdam1976 Před rokem

    Brilliant 👌

  • @jamienesma
    @jamienesma Před rokem

    Thank you.

  • @augischadiegils.5109
    @augischadiegils.5109 Před 2 lety +1

    ❤️❤️❤️❤️❤️

  • @Qpham90
    @Qpham90 Před 6 měsíci +4

    is your name ACTUALLY dom?

  • @derDooFi
    @derDooFi Před rokem

    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

  • @TheTurmanDreams
    @TheTurmanDreams Před 2 měsíci

    thanks !!!!!

  • @foxjonesofficial
    @foxjonesofficial Před 2 lety +1

    love it, first too

  • @canepaper967
    @canepaper967 Před 9 měsíci

    Is it ok if I call you Document Object Model?

  • @DominoPivot
    @DominoPivot Před 3 měsíci

    Eesh, setting up a bad example with your script element without "use strict" or type=module.

  • @davidhand9721
    @davidhand9721 Před 2 měsíci +1

    Wow, don't do this.

  • @paulhetherington3854
    @paulhetherington3854 Před rokem

    How's any Englishman, on this taxan - ught? NTT? ETT= you - N=not. Tm= This maneuvifsz. Movements - moles?