jimmykup jimmykup - 14 days ago 6
Javascript Question

Javascript querySelector to iterate over matching objects and use .innerHTML on them?

I've been using the following code to iterate over matching elements in the DOM. But this apparently does not work if I want to use something like .innerHTML or .innerText.

let courseList = document.querySelectorAll(".course");
for (let course of courseList) {

course.querySelector('.course-number').innerText("Test");

}


Those objects I'm trying to iterate over look like this:

<div class="course">
<div class="course-number">1</div>
</div>
<div class="course">
<div class="course-number">2</div>
</div>


I get this error:

Uncaught TypeError: course.querySelector(...).innerText is not a function(…)


What can I do to make this work?

Answer

Both innerText and innerHTML are not functions whereas there are properties. So, value should be assigned to them as below.

let courseList = document.querySelectorAll(".course");
  for (let course of courseList) {

    course.querySelector('.course-number').innerText = "Test";
    //course.querySelector('.course-number').innerHTML = "Test";

  }
<div class="course">
    <div class="course-number">1</div>
</div>
<div class="course">
    <div class="course-number">2</div>
</div>