skip to Main Content

I am trying to create a element in JavaScript 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 stylize 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.

2

Answers


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

    Login or Signup to reply.
  2. To make it easier to read, you could make the HTML string using backticks.

    function myCustomElement(parentSelector, data) {
      const div = document.createElement('div');
      
      div.innerHTML = `
        <h1>Hello ${data.name}!</h1>
        <caption>This is my custom element!</caption>
        <p style="color: ${data.color}">This text is colored in ${data.color}</p>
       `
       
      const parentNode = document.querySelector(parentSelector);
      parentNode.appendChild(div)
     }
     
     myCustomElement('.container', { name: 'World', color: 'red' })
    <div class="container"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search