0

This is my whole script file (baseURL not shown) which returns 6 objects upon the request on page load (which can be verified if console.log(tabooObject) is used).

My issue is that it's not rendering the 6 div's (tabooObject) on my page, rather it's just HTML written out with the name values, instead of the divs actually being rendered. In other words, I see: <div class="col"> <div class="name">Hey You!</div>... in my browser.

const tabooWidget = document.querySelector('.taboo.widget'); //parent div

fetch(`${baseURL}`)
    .then(response => response.json())
    .then(data => {
        for(let i = 0; i < data.list.length ; i++){
            let name = data.list[i].name; 
            let tabooObject = `
            <div class="col">   
                <div class="name">${name}</div>
            </div>`;
            tabooWidget.append(tabooObject);
        }
    })
    .catch(error => console.error(error))
Jake
  • 85
  • 4
  • There is good answer to this problem here: https://stackoverflow.com/questions/2522422/converting-a-javascript-string-to-a-html-object – Ales Ruzicka Mar 04 '19 at 14:59

2 Answers2

0

.append() expects a node, not an HTML string. Instead of a string create the node this way:

// First create and configure the parent node
let tabooObject = document.createElement("div");
tabooObject.classList.add("col");

// Then its child
let tabooChild = document.createElement("div");
tabooChild.classList.add("name");
tabooChild.textContent = name; // Might need .innerHTML depending on what name holds

// Then append the child to the parent
tabooObject.appendChild(tabooChild);

// Then the whole thing to your widget
tabooWidget.append(tabooObject);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0
let tabooObject = `
<div class="col">   
  <div class="name">${name}</div>
</div>`;

What you have inside tabooObject is a string. If you want to add a string as HTML, you need to use innerHTML.

tabooWidget.innerHTML = tabooObject;

The above code replaces the entire HTML code inside tabooWidget. If you want to append the code, you can do it the plain old string concatenation way: tabooWidget.innerHTML += tabooObject;

Samu
  • 1,448
  • 10
  • 14
  • ok, that does render as HTML- but I only see the last object being rendered; not all 6 divs being created as I would expect (since it within the for loop) – Jake Mar 04 '19 at 15:05
  • 1
    @Jake If you go this route, then the line needs to be `tabooWidget.innerHTML += tabooObject;` so that you don't replace all the inner HTML upon each loop iteration and instead add to it. But, there are performance and security implications to `.innerHTML`, especially when used in a loop, so I wouldn't advise this approach. – Scott Marcus Mar 04 '19 at 15:08
  • Thanks @ScottMarcus – Jake Mar 04 '19 at 15:09