0

i'm trying to get content of div named 'topage' , i did this code

<script type="text/javascript">

       var topagge = document.getElementsByClassName("topage");
             console.log(topagge);

         </script>

in the console it shows like this :

HTMLCollection[1] 0: span.topage ... innerText:"mycontentofdiv" length: 1 proto: HTMLCollection

i want to get the innerText value , i try this code :

 console.log(topagge.innerText);

but in the console it's undefined

please how can i get content of this collection html object ( using the attribut 0 : span.topage wich contain the innerText.

viarnes
  • 2,018
  • 2
  • 19
  • 31
kivok94
  • 303
  • 1
  • 4
  • 11

5 Answers5

2
<script type="text/javascript">
    var topagge =document.getElementsByClassName("topage")[0].innerHTML;
    console.log(topagge);
</script>
Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
Sudhansu Choudhary
  • 3,322
  • 3
  • 19
  • 30
1

This function getElementsByClassName return Collection or return an array of all elements of this class name so you should change your code to be like this

<script type="text/javascript">
    var topagge = document.getElementsByClassName("topage")[0];
    console.log(topagge.textContent); // or topagge.innerHTML;
</script>
0

You need to wait until the HTML docuemnt is fully loaded. Try this:

<script type="text/javascript">
window.onload = function(){
    var topagge = document.getElementsByClassName("topage");
    console.log(topagge);
}
</script>

EDIT:

window.getElementsByClassName returns an array of elements; then, following code will get HTML content of first element:

topagge[0].innerHTML
leo.fcx
  • 6,137
  • 2
  • 21
  • 37
  • yes this is the solution , the problem of undefined is that HTML dosnt complet rendring , but with window.onload it work :) , – kivok94 Jul 14 '15 at 08:12
0

To get the content of a div, use .innerHTML.

document.getElementByClassName is not supported in IE. Can you assign the div an ID, and use document.getElementById instead?

Schien
  • 3,855
  • 1
  • 16
  • 29
0

Try:

console.log(topagge.innerHTML)
ifma
  • 3,673
  • 4
  • 26
  • 38