1

I am trying to inject some javascript into a web page using a very simple js script:

var c = document.getElementsByClassName("main").innerHTML;
alert(c);

I want to set an alert of the text (and only the text) in the div with class="main". Currently the script is making an alert pop up saying 'undefined'. What am I doing wrong, the class name is definitely correct, and I have searched stackoverflow and other sources, having experimented with .innerHTML and .textContent but nothing seems to be able to simply return a var of text.

Will
  • 79
  • 1
  • 1
  • 10
  • since u've tagged jquery, you can use $('.main').text(); if you want the text and $('.main').html() if u want the html – Sushil Apr 30 '15 at 21:27

4 Answers4

4

getElementsByClassName returns an array like object. There is no innerHTML property on it. You need to either act on all the divs returned or a specific one. See docs for further examples. https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

Transcendence
  • 2,616
  • 3
  • 21
  • 31
2

document.getElementsByClassName returns an array because there could be multiple classes with the same class name.

Try doing

var c = document.getElementsByClassName("main")[0].innerHTML;
alert(c);
Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
1

The issue is that you are returning a set of nodes (HTMLCollection). All elements with the class "main" (getElementsByClassName). For example, this will show you the first element's innerHTML

var c = document.getElementsByClassName("main")[0].innerHTML;
alert(c);

However, a more standardized approach for this would be to use querySelector like this

var c = document.querySelector(".main").innerHTML;
alert(c);
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

With getElementsByClassName() it returns an array(in this case a group of elements) which you have to define an offset to mark which one of the elements you want to use:

document.getElementsByClassName("main")[0].innerHTML;//0 returns the first element

JSFiddle Demo

If you want to select all the elements of the class, the easiest way is to use a loop:

    var element =document.getElementsByClassName("main");
    for($i=0;$i<=element.length;$i++){
       alert(element[$i].innerHTML);
    }

JSFiddle Demo

Jacob G
  • 13,762
  • 3
  • 47
  • 67