javascripthtmlecmascript-6string-literalstagged-templates

Error when trying to render a tagged string literal


I'm fetching some data from an API , then for each element returned I'm running this code:


fetch("./apifiles.json").then((res) => res.json()).then((users) => {
        users.usuarios.forEach(e => {

            var div = document.createElement("DIV");

            content = `<h5>usuario:</h5> ${e.name} 
            <h5>id: </h5>${e.id}
            `;

            div.append(content)
            document.body.appendChild(div);
        });
    })

I was expecting the browser to understand and parse the HTML tags inside de "content" variable, however this is what I get in the browser:

<h5>usuario:</h5> srth <h5>id: </h5>0
<h5>usuario:</h5> mthaz <h5>id: </h5>1
<h5>usuario:</h5> oatrz <h5>id: </h5>2

Clearly there is something I'm doing wrong. What can I do so that the browser understands the HTML tags and format it as I expect?

Thanks.


Solution

  • You need to add it as innerHTML to div

    let e = {
      id: 1,
      name: 'some name'
    }
    
    var div = document.createElement("DIV");
    
    let content = `<h5>usuario:</h5> ${e.name} 
            <h5>id: </h5>${e.id}
            `;
    
    div.innerHTML = content
    document.body.appendChild(div);