0

I have an HTML item as follow:

<div id = "myTarget" class="myItem">
    <div class="nestedItem">0/0</div>       <!-- to be updated -->
</div>

I would like to update the content of nestedItem dynamically. However, this JS code fails:

document.getElementById("myTarget").getElementsByClassName("nestedItem").innerHTML = "1/4";

Can someone tell me what went wrong?

J. Doe
  • 441
  • 1
  • 4
  • 13
  • [What do querySelectorAll and getElementsBy* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Andreas Dec 04 '19 at 13:09
  • That said... Use [`document.querySelector()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) instead – Andreas Dec 04 '19 at 13:10
  • ^^ e.g., `document.querySelector("#myTarget .nestedItem").innerHTML = "...";` – T.J. Crowder Dec 04 '19 at 13:10
  • Thank you, gentlemen! I should try that. – J. Doe Dec 04 '19 at 13:22

1 Answers1

1

The issue here is that getElementsByClassName returns an array like object with the elements what you need to iterate. From the documentation:

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class names.

Possible solution could be:

const target = document.getElementById('myTarget');
const items = target.getElementsByClassName('nestedItem');

Array.prototype.forEach.call(items, e => e.innerHTML = '1/4');
<div id="myTarget" class="myItem">
    <div class="nestedItem">0/0</div>
</div>

I hope that helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59