-1

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.

Dean Van Greunen
  • 5,060
  • 2
  • 14
  • 28
Julio Rodríguez
  • 447
  • 1
  • 8
  • 23

2 Answers2

4

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);
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

Instead of div.append(content), use div.innerHTML = content.

Append is used for DOM, not for strings.

Erty Seidohl
  • 4,487
  • 3
  • 33
  • 45
  • You can use `.append` for strings, DOM nodes, or a mix of the two [(see mdn ref).](https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append) `.appendChild` is DOM-node only. `.innerHTML` attempts to parse the text it is assigned as HTML/XML depending on doctype, while `.append` just creates a Text node out of it, regardless of whether or not it might contain valid markup that could be parsed to generate elements for the document. – thmsdnnr Sep 03 '19 at 03:00