1

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 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>
</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!

klaytonme
  • 83
  • 8
  • Does this answer your question? [How to add one specific HTML block with jQuery](https://stackoverflow.com/questions/25385598/how-to-add-one-specific-html-block-with-jquery) – mcky Jul 23 '22 at 08:49
  • i think this is the best way to pass HTML, maybe you need to format string HTML. – Phương Nguyễn Jul 23 '22 at 09:27

2 Answers2

1

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

Reinsbrain
  • 2,235
  • 2
  • 23
  • 35
1

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

Emanuele Scarabattoli
  • 4,103
  • 1
  • 12
  • 21