Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

html; javascript: create element in code and use a template to insert it into the dom

i am trying to create a element in js and inserting it into the dom.

 let div = document.createElement('div');
 div.innerHTML = '<p id="' + selected.val() + '">' + selected.text() + '</p>'; 
document.getElementById('pickedLingua').appendChild(div);

working fine, but the problem is, that when I try to stylise the element, I think this html string will become very hard to read.

Can I maybe create a html template and insert the data into it? There must be a better way then to just create a long html string that no one can read after..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, you can create an HTML template and insert the data into it using JavaScript. Here is an example:

HTML:

<template id="template">
<div>
 <p id="lingua"></p>
</div>
</template>

JavaScript:

// Get a reference to the template
const template = document.getElementById('template');

// Create a new instance of the template
const instance = template.content.cloneNode(true);

// Modify the content of the template instance
const linguaElement = instance.querySelector('#lingua');
linguaElement.id = selected.val();
linguaElement.textContent = selected.text();

// Insert the modified template instance into the DOM
const pickedLingua = document.getElementById('pickedLingua');
pickedLingua.appendChild(instance);

In this example, we’re using the querySelector method to find the #lingua element inside the template instance and modify its id and textContent properties. This will make your code more readable and easier to maintain

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading