-1

As this suggests, we can use Id to get offsetheight. Is there anyway it can be achieved by using a class name??

$("#btn2").click(function(){
    var elmnt = document.getElementById("myId");
    alert("Offset height : "+ elmnt.offsetHeight);
})

$("#btn1").click(function(){
    var elmnt = document.getElementsByClassName("myClass");
    alert("Offset height : "+ elmnt.offsetHeight);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="myId" class="myClass">Lorem Ipsum!</div>

<button id="btn1">Ofset height using Class Name</button>

<button id="btn2">Ofset height using Id</button>

This is not a duplicate of this question, Because I want to know how to select OffsetHeight with class and the answer to this question clears that

ashik
  • 147
  • 3
  • 10
  • If you're using jQuery, rather than `getElementById` or `getElementsByClassName`, you'd typically use `$()`. But in any case, see the linked question's answers for why your code above doesn't work. – T.J. Crowder Aug 28 '18 at 10:22
  • [What is the jQuery equivalent to offsetHeight?](https://stackoverflow.com/questions/34079032/what-is-the-jquery-equivalent-to-offsetheight) – Alive to die - Anant Aug 28 '18 at 10:24

1 Answers1

4

getElementsByClassName will return collection of element. You need to find first element in matched set and then use offsetHeight property on it:

var elmnt = document.getElementsByClassName("myClass")[0];

$("#btn2").click(function(){
    var elmnt = document.getElementById("myId");
    console.log("Offset height : "+ elmnt.offsetHeight);
})

$("#btn1").click(function(){
    var elmnt = document.getElementsByClassName("myClass")[0];
    console.log("Offset height : "+ elmnt.offsetHeight);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="myId" class="myClass">Lorem Ipsum!</div>

<button id="btn1">Ofset height using Class Name</button>

<button id="btn2">Ofset height using Id</button>
Turnip
  • 35,836
  • 15
  • 89
  • 111
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125