Recuvan Recuvan - 5 months ago 10
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

Answer

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

var z = document.querySelector('.time span').innerHTML;
console.log(z)
<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);
});
console.log(z)
<div class="time">Time: <span>500</span>
</div>
<div class="time">Time: <span>200</span>
</div>

Comments