Home > Blockchain >  How i can use "querySelectorAll"?
How i can use "querySelectorAll"?

Time:01-03

My html:

<label for="answer_1" ><input type="radio" id="answer_1">Answer</label>
<label for="answer_2" ><input type="radio" id="answer_2">Answer</label>
<label for="answer_3" ><input type="radio" id="answer_3">Answer</label>

My JS:

var answers = ["Answer_1","Answer_2","Answer_3"];
var answer_labels = document.querySelectorAll(".answer_label");
for (var i = 0; i < answers.length; i  ){
    answer_labels[i].innerText = answers[i]
}

When I want to set text to my labels, I get error:

Uncaught TypeError: Cannot set properties of undefined (setting 'innerText')

CodePudding user response:

You have a syntax error in the for loop.

change for (var i = 0; i < .length; i )

to for (var i = 0; i < answer_labels.length; i )

var answers = ["Answer_1","Answer_2","Answer_3"]
var answer_labels = document.querySelectorAll(".answer_label");
for (var i = 0; i < answer_labels.length; i  ){
    answer_labels[i].innerText = answers[i];
}
  <label for="answer_1" ><input type="radio" name="choice" id="answer_1">Answer</label>
        <label for="answer_2" ><input type="radio" name="choice" id="answer_2">Answer</label>
        <label for="answer_3" ><input type="radio" name="choice" id="answer_3">Answer</label>

CodePudding user response:

If you just want to replace the labels without destroying the radio button inputs inside you should maybe do something like this:

var answers = ["Answer_1","Answer_2","Answer_3"]
document.querySelectorAll(".answer_label").forEach((l,i)=>{
  l.innerHTML=l.querySelector("input").outerHTML answers[i];
})
<label for="answer_1" ><input type="radio" name="choice" id="answer_1">Answer</label>
<label for="answer_2" ><input type="radio" name="choice" id="answer_2">Answer</label>
<label for="answer_3" ><input type="radio" name="choice" id="answer_3">Answer</label>

CodePudding user response:

It's a good practice to store the length of the array to iterate into a variable before iterating. This way you can also make sure, that the iteration won't go past the length of the other array you refer in the loop.

There's also a logical error in the code. Rewriting innerText of the labels will remove the nested input elements. I've moved the inputs out of the labels in the code below.

var answers = ["Answer_1", "Answer_2", "Answer_3", "Answer_4"];
var answerLabels = document.querySelectorAll(".answer_label");
var length = Math.min(answers.length, answerLabels.length);

for (var i = 0; i < length; i  ) {
  answerLabels[i].innerText = answers[i];
}
<label for="answer_1" >Answer</label><input type="radio" id="answer_1">
<label for="answer_2" >Answer</label><input type="radio" id="answer_2">
<label for="answer_3" >Answer</label><input type="radio" id="answer_3">

CodePudding user response:

the problem was that I did not specify "<!DOCTYPE html>" in html file... thanks everyone

  • Related