I have around 6 div
on a page and only one of them needs to be visible at a time. During page load, I hide all the other divs except the first one.
Here's my HTML structure.
<div id="A1">
</div>
<div id="A2">
</div>
<div id="B1">
</div>
<div id="B2">
</div>
<div id="C1">
</div>
<div id="C1">
</div>
Here's what I do to hide them :-
$(document).ready(function(){
$("#A2").hide();
$("#B1").hide();
$("#B2").hide();
$("#C1").hide();
$("#C2").hide();
});
How would I get the ID of the visible div? I have tried :-
var current_div = $("div:visible");
current_div_id = current_div.attr('id');
Output :- Undefined
var current_div = $("div:visible");
current_div_id = current_div[0].id;
Output :- Blank
What am I getting wrong ?
Try this:
var current_div = $("div:visible").attr("id");
$( 'body' ).text( current_div );
well, your code is working actually, and I can get id
using both methods. You're missing something else here, check console
what else do you get.
just one issue, you won't get consistent results as you've duplicate id
on your page C1
, twice.
<div id="A1">
A1
</div>
<div id="A2">
A2
</div>
<div id="B1">
B1
</div>
<div id="B2">
B2
</div>
<div id="C1">
C1
</div>
<div id="C2">
C2
</div>
<p id = "one"></p>
<p id = "two"></p>
$(document).ready(function(){
$("#A1").hide();
$("#B1").hide();
$("#B2").hide();
$("#C1").hide();
$("#C2").hide();
});
var current_div = $("div:visible");
current_div_id = current_div[0].id;
$("#one").text("ID: "+current_div_id);
var current_div = $("div:visible");
current_div_id = current_div.attr('id');
$("#two").text("ID using second method: "+current_div_id);
Fixed it. Posting a solution to help future peeps.
It seems that jquery is unable to find the current div using my above code. What I did is, added a common class to all the divs. Like this :-
<div id="A1" class="divs">
</div>
<div id="A2" class="divs">
</div>
<div id="B1" class="divs">
</div>
<div id="B2" class="divs">
</div>
<div id="C1" class="divs">
</div>
<div id="C1" class="divs">
</div>
And now I modified my JS in this way :-
var current_div = $(".divs:visible");
current_div_id = current_div[0].id;
And it worked. So if you're in the same problem, remember to have a common class for all the divs.