Home > OS >  var numbers = document.querySelectorAll("#box1 , #box2");
var numbers = document.querySelectorAll("#box1 , #box2");

Time:09-18

I have problem with my javascript code why that function didn't get the multiple id's

var numbers = document.querySelectorAll("#box1 , #box2");
for(i=0; i<10; i  ){
    var span = document.createElement('span')
    span.textContent = i;
    numbers.appendChild(span);
}
/////////////////////////
<div id="box1"></div>(this is the div where is doesn't get)

CodePudding user response:

Unlike jQuery you cannot run an action of the entire node list (array of elements). You have to forEach all the elements.

var numbers = document.querySelectorAll("#box1 , #box2");
numbers.forEach(function(number) {

  // this is almost exact copy of your code
  for (i = 0; i < 10; i  ) {
    var span = document.createElement('span')
    span.textContent = i;
    number.appendChild(span);
  }

})
<div id="box1"></div>
<div id="box2"></div>

CodePudding user response:

why dont you use getElementById?

use querySelectorAll when you have many div with same classname

const box1 = document.getElementById("box1")
const box2 = document.getElementById("box2")

const box = document.querySelectorAll(".box")

const box_1 = document.querySelector("#box1")
const box_2 = document.querySelector("#box1")
    <div id="box1" ></div>
    <div id="box2" ></div>

  • Related