2

I have this code

<div style="height:500px;display:none"></div>
<div style="height:1000px;"></div>

<script>

$(document).ready(function() {

     var visible_elem_height = $('div').is(':visible').height()

     alert( visible_elem_height )

});

</script>

but my code Doesn't work , So what do u suggest ?

Danin Na
  • 359
  • 2
  • 10

4 Answers4

3

.is() return a boolean value so your script will fail, instead you need

$(document).ready(function () {

    var visible_elem_height = $('div:visible').height();
    //or var visible_elem_height = $('div').filter(':visible').height()

    alert(visible_elem_height)

})
Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
1

$('div').is(':visible') returns true/false depending on the visibility of your element. On the other hand, .height() function is applied on the element and NOT on the boolean output. Therefore, $('div').is(':visible').height() will simply not work.

To achieve the desired behaviour, use the :visible selector $('div:visible').height()

$(document).ready(function() {

     var visible_elem_height = $('div:visible').height()

     alert( visible_elem_height )

});

plunkr

nalinc
  • 7,184
  • 21
  • 32
1

Try utilizing .filter()

$(document).ready(function() {
  var div = $("div").filter(function(i, el) {
    return $(el).is(":visible")
  });
  
  if (div.length > 0) {
    alert(div.height())
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div style="height:500px;display:none"></div>
<div style="height:1000px;"></div>
guest271314
  • 1
  • 10
  • 82
  • 156
0

The statement is(':visible') returns true or false as output. If you want to get the height of the element, you can directly get it using the .height() method.

Mivaweb
  • 5,113
  • 3
  • 21
  • 49
Abhi
  • 1
  • 2