Home > Software design >  Right way to fill HTML from JS
Right way to fill HTML from JS

Time:07-23

I am currently working on a page that requires filling a div programmatically with a bunch of HTML like this sample code

<div id="Element">
  <div >
    <div >
      <span>Editor Menu</span>
      <img src="https://github.com/..." />
    </div>
    <div >
      <img src="https://github.com/..." />
    </div>
  </div>
</div>

right now, I am doing this as follows

Element.innerHTML = "<div class='tooltiptext top both'><div class='editorMenuButton'><span>Editor Menu</span><img src='https://github.com/...' /></div><div class='diceButton'><img src='https://github.com/...' /></div></div>";

which definitely works, but using a string to pass HTML seems like probably not the right/best/professional way to do it. Is there a better way?

Thanks!

CodePudding user response:

Without involving any external libraries/frameworks, plain javascript allows you to create elements:

var mydiv = document.createElement('div');

see https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement ]

You can add various properties as needed:

mydiv.className = 'tooltiptext top both';

see https://developer.mozilla.org/en-US/docs/Web/API/Element

Then append these created elements to other elements

Element.appendChild(mydiv);

see https://developer.mozilla.org/en-US/docs/Web/API/Element/append

There are several libraries that make this a bit easier such as metaflux

CodePudding user response:

Well, in some cases make sense to use a string, but if you need something more structured, you may use document.createElement

https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

  • Related