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..
>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