best way to inject html using javascript

Viewed 109698

I'm hoping that this isn't too subjective. I feel there is a definitive answer so here goes.

I want to create this html on the fly using JS (no libraries):

<a href="#" id="playButton">Play</a>
<a href="javascript: void(0)" id="muteUnmute">Mute</a>
<div id="progressBarOuter"> 
  <div id="bytesLoaded"></div>
    <div id="progressBar"></div>
</div>
<div id="currentTime">0:00</div>
<div id="totalTime">0:00</div>

using javascript. I know I can do this using createElement etc but it seems extremely long winded to do this for each element. Can anyone suggest a way to do this with more brevity.

I do not have access to a library in this project....so no jquery etc.

10 Answers

If you live in 2019 and beyond read here.

With JavaScript es6 you can use string literals to create templates.

create a function that returns a string/template literal

function videoPlayerTemplate(data) {
    return `
        <h1>${data.header}</h1>
        <p>${data.subheader}</p>
        <a href="#" id="playButton">Play</a>
        <a href="javascript: void(0)" id="muteUnmute">Mute</a>
        <div id="progressBarOuter"> 
            <div id="bytesLoaded"></div>
            <div id="progressBar"></div>
        </div>
        <time id="currentTime">0:00</time>
        <time id="totalTime">0:00</time>
    `
}

Create a JSON object containing the data you want to display

var data = {
     header: 'My video player',
     subheader: 'Version 2 coming soon'
}

add that to whatever element you like

const videoplayer = videoPlayerTemplate(data);
document.getElementById('myRandomElement').insertAdjacentHTML("afterbegin", videoplayer);

You can read more about string literals here

here's 2 possible cases :

  1. Your HTML is static
  2. Your HTML is dynamic

solution 1

In this case, wrap your HTML in double quotes, make it a string and save it in a variable. then push it inside HTML, here's a demo

HTML

<div id="test"></div>

JavaScript

let selector = document.querySelector("#test");

let demo_1 = "<div id='child'> hello and welcome</div>"
selector.innerHTML = demo_1;

solution 2

In this case, wrap your HTML in back ticks, make it a template literal and save it in a variable. then push it inside HTML, here, you can use variables to change your content. here's a demo

HTML

<div id="test"></div>

JavaScript

let selector = document.querySelector("#test");

let changes = 'hello and welcome'
let demo_1 = `<div id='child'>${changes}</div>`
selector.innerHTML = demo_1;
Related