Recuvan Recuvan - 7 months ago 13
Javascript Question

Extract what's inside of "span" that's inside of a class

I'm looking for a way to set the variable z as 500

I tried the following so far:

z = +(document.getElementsByClassName("time span").innerHTML)

But it gives me an output of NaN

enter image description here


You can use querySelector() instead and select .time span

var z = document.querySelector('.time span').innerHTML;
<div class="time">Time: <span>500</span></div>

In case you want to add time from multiple span's to z var you can use querySelectorAll() which returns NodeList and transform it to array and then use forEach loop and add each value of span to z

var z = 0;

Array.from(document.querySelectorAll('.time span')).forEach(function(e) {
  z += Number(e.innerHTML);
<div class="time">Time: <span>500</span>
<div class="time">Time: <span>200</span>