1

I have

<div class="ce">
  <div class="lotB">9</div>
  <div class="lotB">3</div>
  <div class="lotB">28</div> == $0
</div>

I'm trying to get these three numbers 9, 3, 28 but I can't get this to work :s

Already tried several different things and I also read about innerText and tried to get it work by going through the class ce like that

var x = document.getElementsByClassName("ce");
for (var i = 0; i < x.length; i++) {
  var numbers = x[i].innerText;
  alert(numbers);
}

But also this didn't give me anything : /

How do you get this inner text of each these classes, so I got the numbers 9, 3, 28?

Mikev
  • 2,012
  • 1
  • 15
  • 27

6 Answers6

4

You can use querySelectorAll() to target all the div inside the class. Change the selector to:

document.querySelectorAll(".ce > div");

var x = document.querySelectorAll(".ce > div");
for (var i = 0; i < x.length; i++) {
  var numbers = x[i].innerText;
  alert(numbers);
}
<div class="ce">
  <div class="lotB">9</div>
  <div class="lotB">3</div>
  <div class="lotB">28</div> == $0
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
2

You need to do var x = document.getElementsByClassName("lotB") as lotB has that values. Also note that if you want to do any arithmetic operations on that values you need to use parseInt(numbers) to get its numeric representation.

var x = document.getElementsByClassName("lotB");
for (var i = 0; i < x.length; i++) {
  var numbers = x[i].innerText;
  alert(numbers);
}
<div class="ce">
  <div class="lotB">9</div>
  <div class="lotB">3</div>
  <div class="lotB">28</div>
</div>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

var x = document.getElementsByClassName("lotB");
for (var i = 0; i < x.length; i++) {
  var numbers = x[i].textContent;
  alert(numbers);
}
<div class="ce">
  <div class="lotB">9</div>
  <div class="lotB">3</div>
  <div class="lotB">28</div> == $0
</div>
CoderPi
  • 12,985
  • 4
  • 34
  • 62
1
var numbers = x[i].textContent;

Rather than using InnerHtml use textContent

Difference between textContent vs innerText

Suresh
  • 923
  • 1
  • 10
  • 21
1

You could use spread syntax

[...document.getElementsByClassName("lotB")].forEach(e=>console.log(e.innerText));
<div class="ce">
  <div class="lotB">9</div>
  <div class="lotB">3</div>
  <div class="lotB">28</div> == $0
</div>
Emeeus
  • 5,072
  • 2
  • 25
  • 37
1

give each elements the same class

  <div class="ce">
   <div class="lotB">9</div>
   <div class="lotB">3</div>
   <div class="lotB">28</div> == $0
  </div>

the key here is that it says "get elements" and therefore it can handle multiple classes that are the same

var x = document.getElementsByClassName("lotB");
for (var i = 0; i < x.length; i++) {
  var numbers = x[i].innerHtml;
  alert(numbers);
}

i use .innerHtml here

Tom Edwards
  • 124
  • 1
  • 13