简体   繁体   中英

Right way to fill HTML from JS

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!

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);

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM