3

I have been using classes on my web and now I want to calculate height of a class. It is a unique class (not being used anywhere except one). I tried offsetHeight and height in Javascript but unable to find any output. Suppose here is my code.

<div class="example">some text some text some text some text some text".</div>
<button onclick="myFunction()">Try it</button>

Here is Javascript

<script>
function myFunction() {
document.getElementsByClassName("example").offsetHeight="300px";
}
</script>

Error:
I'm not getting any output/error anywhere on the page or in the console. Hope you guys will help me and I want only solution in Javascript not in jQuery or any other library. Any help will be appreciated.

6
  • Try document.getElementsByClassName("example")[0].offsetHeight="300px"; Nov 27, 2015 at 11:00
  • 2
    @Jahanzaib Asgher do you want set or get Height? Nov 27, 2015 at 11:04
  • @Alexander I wanted to get height Nov 27, 2015 at 11:04
  • @Jahanzaib Asgher look at my example below, I've added variants how you can get and set height Nov 27, 2015 at 11:07
  • @JahanzaibAsgher Have you seen the answerS? Nov 27, 2015 at 11:17

4 Answers 4

3

getElementsByClassName returns HTMLCollection, so you need get first element from this collection

function myFunction() {
  var element = document.getElementsByClassName("example")[0];

  // get height
  var height = element.offsetHeight;
  console.log(height);

  // set height
  element.style.height = '100px';
}
<div class="example">some text some text some text some text some text".</div>
<button onclick="myFunction()">Try it</button>

0
1

You need to use the integral value on the object list index:

document.getElementsByClassName("example")[0].offsetHeight = 300;

The getElementsByClassName returns an array of matched elements. So you are actually applying that function on an array, which has no effect.

Working Snippet

function myFunction() {
  alert(document.getElementsByClassName("example")[0].offsetHeight);
}
<div class="example">some text some text some text some text some text".</div>
<button onclick="myFunction();">Try it</button>

1

The getElementsByClassName() will return an array of objects so you have to specify wich object you want, e.g :

var class_height = document.getElementsByClassName("example")[0].offsetHeight;

To select the first object.

Hope this helps.

0

change your code like this.will work

var height = document.getElementsByClassName("example")[0].offsetHeight;    
console.log(height);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.