user5748960
user5748960

Reputation:

How do you get the inner text inside these classes with javascript?

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?

Upvotes: 1

Views: 1226

Answers (6)

Tom Edwards
Tom Edwards

Reputation: 124

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

Upvotes: 1

Emeeus
Emeeus

Reputation: 5260

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>

Upvotes: 1

Suresh
Suresh

Reputation: 923

var numbers = x[i].textContent;

Rather than using InnerHtml use textContent

Difference between textContent vs innerText

Upvotes: 1

Mamun
Mamun

Reputation: 68933

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>

Upvotes: 4

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

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>

Upvotes: 2

CoderPi
CoderPi

Reputation: 13211

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>

Upvotes: 1

Related Questions