neethu neethu - 5 months ago 34
jQuery Question

How to find the index of a div which having the property display:block in jQuery?

I need to find the index of a div which having the property display:block,in jQuery.

html structure is like :

<div id="bb-bookblock" class="bb-bookblock bb-vertical" >

<div class="bb-item" style="display: none;"> </div>
<div class="bb-item" style="display: none;"> </div>
<div class="bb-item" style="display: none;"> </div>
<div class="bb-item" style="display: block;"> </div>
<div class="bb-item" style="display: none;"> </div>
<div class="bb-item" style="display: none;"> </div>
</div>


where the child div are generated dynamically

Answer

Use attribute contains selector or :visible pseudo-class selector to get the element and then get it's index using index() method.

console.log(
  $('.bb-item[style*="display: block"]').index(),
  $('.bb-item:visible').index()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bb-bookblock" class="bb-bookblock bb-vertical">
  <div class="bb-item" style="display: none;"></div>
  <div class="bb-item" style="display: none;"></div>
  <div class="bb-item" style="display: none;"></div>
  <div class="bb-item" style="display: block;"></div>
  <div class="bb-item" style="display: none;"></div>
  <div class="bb-item" style="display: none;"></div>
</div>

Comments