key2learn
key2learn

Reputation: 152

Getting the id of a div which is being displayed

I have the following HTML code:

<div id="skills">
    <div class="items" id="items1" style="display:none">1</div>
    <div class="items" id="items2" >2</div>
    <div class="items" id="items3" style="display:none">3</div>
    <div class="items" id="items4" style="display:none">4</div>
    <div class="items" id="items5" style="display:none">5</div>
</div>

I need to access the div which is being displayed and get it's id. Please let me know how can I do this ?

Upvotes: 2

Views: 5161

Answers (3)

Lix
Lix

Reputation: 47956

jQuery has a dedicated :visible selector. You can use this to match any element that is being displayed.

https://api.jquery.com/visible-selector/

Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.

Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout.

So to use this in your scenario, you would have something like this:

var desired_id = $('.items:visible').prop('id');

Keep in mind that if more than one element is matched using .items:visible, you will only get the first matched element's id and not all of them.

Upvotes: 2

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

You can use .not() which remove the elements from the set of matched elements.

var divId = $("div.items").not(":hidden").prop("id");

Working Demo

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use the :visible selector:

var visibleId = $('.items:visible').prop('id'); // = 'items2'

Upvotes: 4

Related Questions