Home > Blockchain >  Loop through DIVS / Elements
Loop through DIVS / Elements

Time:05-08

Quick Explanation:

My code looks like that:

*

  • div class 1 (in these divs 1-4 -> there a nested divs for Name / Score / ...)
  • div class 2
  • div class 3
  • div class 4
  • ...
*

I change the values with JS

  • document.getElementById('1').textContent=data.user[0].Score "M";
    document.getElementById('1').textContent=data.user[1].Score "M";
    document.getElementById('3).textContent=data.user[2].Score "M";
    document.getElementById('3).textContent=data.user[3].Score "M";

I know that I can FOR LOOP through this but my problem is:

I want to loop through the children of my "table" class. Therefore I dont have to write the numbers for "class=1" ... "class=2" 3 4 5 6

CodePudding user response:

As I understood you correct you want to loop through the tables children and catch the contained divs by this right? If so please try to select all divs which are children of the table by the help of document.querySelectorAll. Done that you're able to loop through them like:

const tableDivs = document.querySelectorAll("table div");

[...tableDivs].forEach((div, index) => {
  div.textContent = data?.user[index]?.Score   "M";
});

Since I only saw some pieces of code I'm not fully able to check the outcome. You might need to adapt some pieces to make it work but I'm sure you get the idea right?

CodePudding user response:

First you need to get all the child elements with a variable like:
var children = document.querySelector('.container').children;

Then you need a JS loop to loop through them which you can do with:
for (var i = 0; i < children.length; i ) { /* commands */ }

Then you need a counter that you can easily declare with a variable:
var counter = 1;

You rise that counter after each loop by declaring inside the loop:
var counter = counter 1;

To add a class list with numebring you need to add a continios class-name through combing the class-name with the counter as variable:
var className = "class-" counter;

Then you can add this class-name to every element by using:
child.classList.add(className);

var children = document.querySelector('.container').children,
    counter = 1;
    
for (var i = 0; i < children.length; i  ) {   
  var child = children[i];
  var className = "class-"   counter;
  
  /* just adds a counter to the innerHTML to demonstrate */
  child.innerHTML = "class = class-"   counter;
  
  /* what you actually want */
  child.classList.add(className);
  
  /* rises the counter */
  var counter = counter   1;   
}
<div >
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

  • Related