0

I'm trying to figure out my content div's height when overflowed with content thanks to the nifty .scrollHeight javascript function. However, when I alert this height I'm getting an "undefined" result. I'm fairly new to javascript so I might have made some really dumb mistake:

http://codepen.io/anon/pen/GJOVvd

basically looks like this in my html (because Stack Overflow doesn't let me just post codepen links):

<script>var intElemScrollHeight = document.getElementsByClassName("content").scrollHeight;
alert(intElemScrollHeight + " px");
</script>

I made a quick codepen which really resembles my problem, except that the height of my content container in my actual project depends on the height of the header, but that changes naught I believe, as I'm still getting that "undefined".

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
chactas
  • 11
  • 1
  • 3

2 Answers2

0

document.getElementsByClassName returns an array of elements matching the given class name. This might be only one, or multiple. The change you have to do is to get the first element of the results array:

var intElemScrollHeight = document.getElementsByClassName("content")[0].scrollHeight;
alert(intElemScrollHeight + " px");

For more information on getElementsByClassName see MDN: Document.getElementsByClassName

If you have multiple elements with a class content what you have to do is to iterate over the result. See this stackoverflow thread: Iterating over Results of getElementsByClassName. Essentially, the solution is the following:

var els = document.getElementsByClassName("myclass");

Array.prototype.forEach.call(els, function(el) {
    // Do stuff with the element
    console.log(el.tagName);
});
Community
  • 1
  • 1
  • 1
    Very nice and detailed answer, and quickly too! Works perfectly both on my little codepen and on my site. Thank you for even going the extra mile and showing me how to iterate over the results of multiple class names! – chactas Jun 26 '15 at 00:05
0

You should use var intElemScrollHeight = document.getElementsByClassName("content")[0].scrollHeight;

because if you try to getElementByClassName, it will return the array that includes all html elements that have "content" class. So you have to give index 0 as in your case it has only div or html element that has "content" class. It is advised to use document.GetElementById if there are more that one element assigned same class.