0

I'm trying to take div innerHTML, but I cant give that div ID so I try to take it by classname. Here is that html:

<div class=" nicEdit-main    " style="width: 499px; margin: 4px; min-height: 149px; overflow: hidden;" contenteditable="true"><div align="center"><ol><li><sub><font size="5">+++</font></sub></li></ol></div></div>

And here is what I've tried to do:

document.getElementsByClassName(" nicEdit-main ").innerHTML;

Bu it returns unidefined. What can i do to take that innerHTML?

j08691
  • 204,283
  • 31
  • 260
  • 272
McLaren
  • 776
  • 1
  • 10
  • 23
  • 1
    Don't you see that `Elements` is plural? It returns a list of all the elements with that class, not just one. So how can you take the innerHTML of all of them at once? – Barmar Aug 27 '15 at 13:30
  • Why can you not give your div an ID? Although I have provided an answer to your question, I imagine this is a bigger problem that needs solving. – Sam Aug 27 '15 at 13:36
  • Because NicEditor creates this html. – McLaren Aug 27 '15 at 13:38

2 Answers2

4

document.getElementsByClassName returns an array and not a single element (note the s in the middle).

IF your element is the only element of that class, then it will be the first element of the array and so document.getElementsByClassName(" nicEdit-main ")[0].innerHTML will return what you want.

However, this is very bad practice as classes are meant as a reference to many elements and not one single element. I recommend giving the div a unique ID and selecting it using that instead.

Sam
  • 3,070
  • 3
  • 20
  • 26
  • careful with this function.... getElementsByClassName() not works in any browsers... – DZanella Aug 27 '15 at 13:32
  • @DZanella - I don't think you are correct. See here: http://caniuse.com/#feat=getelementsbyclassname – Sam Aug 27 '15 at 13:33
  • But still it's undefined look https://jsfiddle.net/fNPvf/18419/ – McLaren Aug 27 '15 at 13:36
  • No, it isn't - you are not alerting the result correctly. See here: https://jsfiddle.net/fNPvf/18420/ (click on the result to see the alert.) – Sam Aug 27 '15 at 13:41
0

Try:

document.getElementsByClassName("nicEdit-main")[0].innerHTML
amespower
  • 907
  • 1
  • 11
  • 25