Create dynamic html through javascript

Asked

Viewed 521 times

1

I am developing a system (for study) and I came across a situation and thought about the different possibilities of doing it. On my website, when clicking the "Create Box" button a div with images, texts, other Ivs that are inside other Ivs, summarizing, a lot of html code. I usually do this kind of thing using the createelement() method, however, with this amount of html the javascript code would become very complex and confusing, hence I had an idea of playing all the html within a javascript function and returnsby making sure that through innerHTML I could add as many boxes as I wanted just by clicking on the "Create Box" button. Here comes the question, is this an acceptable way to create dynamic html? That is, would it be good or bad practice? If it is a bad practice, as an experienced developer would do?

Example:

//Essa função está em arquivo separado
function htmlCode() {
    return '<div> MUITO CÓDIGO HTML AQUI </div>';
}
...

<div id="container"></div>
<input type="button" id="addBox" /> 

...
<script> document.getElementById('addBox').onclick = function() { 
document.getElementById('container').innerHTML += htmlCode();
} </script>

1 answer

2

You can use the tag template:

Reference: https://www.w3schools.com/tags/tag_template.asp

function showContent() {
  var temp = document.getElementsByTagName("template")[0];
  var clon = temp.content.cloneNode(true);
  document.body.appendChild(clon);
}
<!--Exemplo-->
<template>
  <h2>Flores</h2>
<h3>Flor é a estrutura reprodutora característica das plantas angiospérmicas. Sua função é produzir sementes através da reprodução sexuada. Para as plantas, as sementes representam o embrião, que irá germinar quando entrar em contato com um substrato propício; as sementes são o principal meio através do qual as espécies de espermatófitas se perpetuam e se propagam.</h3>
  <img src="https://www.w3schools.com/tags/img_white_flower.jpg" width="214" height="204">
</template>


<h1>A tag template</h1>

<p>Clique no botão para obter o conteúdo de um modelo e exibi-lo na página da web.</p>

<button onclick="showContent()">Show content</button>

<template>
  <h2>Flower</h2>
  <img src="https://www.w3schools.com/tags/img_white_flower.jpg" width="214" height="204">
</template>

  • Thank you so much, that’s really what I needed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.