Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add values from an array as textContent with JavaScript

I’m having trouble figuring out how to add the values from an array as .textContent of a div.

What I want to happen is if I receive an array (topics) I want the contents of the array to be set as the .textContent of the elements with class="tab".

I feel like this code is correct, but doesn’t seem to be working. Any ideas?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const Tabs = (topics) => {
  const tabsTopics = document.createElement("div");
  const tabsOne = document.createElement("div");
  const tabsTwo = document.createElement("div");
  const tabsThree = document.createElement("div");

  tabsTopics.classList.add("topics");
  tabsOne.classList.add("tab");
  tabsTwo.classList.add("tab");
  tabsThree.classList.add("tab");

  tabsTopics.appendChild(tabsOne);
  tabsTopics.appendChild(tabsTwo);
  tabsTopics.appendChild(tabsThree);

  document.querySelectorAll(".tab").forEach((el, i) => {
      el.textContent = topics[i];
    });

  return tabsTopics;
}

const topics = ['1', '2', '3'];

document.getElementById('container').appendChild(Tabs(topics));
<div id="container"></div>

>Solution :

tabsTopics has not been inserted in the DOM so the document.querySelectorAll(".tab") will not find its children.

You should do

tabsTopics.querySelectorAll(".tab").forEach((el, i) => {
  el.textContent = topics[i];
});

instead.


const Tabs = (topics) => {
  const tabsTopics = document.createElement("div");
  const tabsOne = document.createElement("div");
  const tabsTwo = document.createElement("div");
  const tabsThree = document.createElement("div");

  tabsTopics.classList.add("topics");
  tabsOne.classList.add("tab");
  tabsTwo.classList.add("tab");
  tabsThree.classList.add("tab");

  tabsTopics.appendChild(tabsOne);
  tabsTopics.appendChild(tabsTwo);
  tabsTopics.appendChild(tabsThree);

  tabsTopics.querySelectorAll(".tab").forEach((el, i) => {
      el.textContent = topics[i];
    });

  return tabsTopics;
}

const topics = ['1', '2', '3'];

document.getElementById('container').appendChild(Tabs(topics));
<div id="container"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading