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

КОМЕНТАРІ • 55

  • @user-rz4gs1qm6n
    @user-rz4gs1qm6n 2 роки тому +17

    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 Рік тому +20

    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 11 місяців тому

      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 8 місяців тому +1

      Then what to use man?

    •  8 місяців тому +1

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

    • @bigfrostishere
      @bigfrostishere 5 місяців тому

      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.

  • @JeanBotan
    @JeanBotan 9 місяців тому +2

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

  • @Qpham90
    @Qpham90 9 місяців тому +8

    is your name ACTUALLY dom?

    • @Panthon69
      @Panthon69 Місяць тому

      Ja hy is Dom

    • @functionfofx
      @functionfofx 29 днів тому

      ​@Panthon69 are you south african?😅

    • @Panthon69
      @Panthon69 28 днів тому

      @@functionfofx prety obvs lmao

  • @edmundogriffin3448
    @edmundogriffin3448 Місяць тому

    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

  • @sfmg
    @sfmg 2 роки тому +2

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

  • @teterposh7042
    @teterposh7042 2 роки тому +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

  • @apgeorgiev
    @apgeorgiev 2 роки тому +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 2 роки тому

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

    • @apgeorgiev
      @apgeorgiev 2 роки тому

      @@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 Рік тому

      Anatoli hi! Can you provide some code snippet, please

  • @danielsladecek8258
    @danielsladecek8258 Рік тому +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

  • @rajankhunt7002
    @rajankhunt7002 Рік тому +1

    Which code font family use in this video

  • @aer0449
    @aer0449 Рік тому +1

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

  • @Hustlalyfe44
    @Hustlalyfe44 9 місяців тому

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

  • @lonewolfcoding5208
    @lonewolfcoding5208 Рік тому

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

  • @sangeethasancharaya6870
    @sangeethasancharaya6870 2 місяці тому

    every time i code document.getelementbyId the console says document is not defined. how could i overcome this problem.

    • @dcode-software
      @dcode-software  2 місяці тому +1

      I've made a video that might contain the solution to your problem:
      ua-cam.com/video/d14vAVDCxEg/v-deo.html

    • @sangeethasancharaya6870
      @sangeethasancharaya6870 2 місяці тому

      @@dcode-software thanks for the response

  • @GetShwiftyInHere
    @GetShwiftyInHere 11 місяців тому

    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?

  • @clashoffans496
    @clashoffans496 2 роки тому +1

    Is using innerHTML safe for parsing?

  • @hericklenin
    @hericklenin 2 роки тому +1

    Very cool. Thank you dcode.

  • @georegio
    @georegio Рік тому

    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 Рік тому

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

  • @elyasmohammadi3163
    @elyasmohammadi3163 2 роки тому +1

    very good technique!!!

  • @rmlacana581
    @rmlacana581 2 роки тому

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

  • @DoubleNation
    @DoubleNation 2 роки тому +1

    As always very very nice content and exactly on point!

  • @isamal-abbasi2392
    @isamal-abbasi2392 Рік тому

    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 Рік тому

      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

  • @derDooFi
    @derDooFi Рік тому

    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

  • @canepaper967
    @canepaper967 Рік тому

    Is it ok if I call you Document Object Model?

  • @DominoPivot
    @DominoPivot 6 місяців тому

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

  • @gensys244
    @gensys244 2 роки тому

    great ! thank you well done

  • @TheTurmanDreams
    @TheTurmanDreams 5 місяців тому

    thanks !!!!!

  • @foxjonesofficial
    @foxjonesofficial 2 роки тому +1

    love it, first too

  • @jamienesma
    @jamienesma Рік тому

    Thank you.

  • @jasinAmsterdam1976
    @jasinAmsterdam1976 Рік тому

    Brilliant 👌

  • @augischadiegils.5109
    @augischadiegils.5109 2 роки тому +1

    ❤️❤️❤️❤️❤️

  • @davidhand9721
    @davidhand9721 5 місяців тому +1

    Wow, don't do this.

  • @paulhetherington3854
    @paulhetherington3854 Рік тому

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