I have a modal popup which has different divs for different messages, now i want to hide each div and show just the one I need to show. instead of writing out each div id and setting it to hidden i wanted to do a loop so i put my divs inside an UL list. But I can't seem to figure out how to hide just the divs inside that UL list..

$("#panels li").each(function (i) {

$('div').toggle();

});

<ul id="panels">

<li><div id="dvError" class="hiddencol">this is div 1</div></li>

<li><div id="dvconfirm" class="hiddencol">this is div 2</div></li>

</ul>

for some reason when I do this it hides them but it hides every div on my page :(

网友答案:

You can just do

$("#panels").find('div').toggle();

or

$("#panels div").toggle();

or if you want to keep your loop

$("#panels li").each(function (i) {
$(this).find('div').toggle();
});

$('div').toggle(); <-- this will toggle every div on your page

网友答案:

try this

$("#panels li").each(function (i) {
$(this).find('div').toggle();
});

网友答案:

The reason is simple

$('div').toggle();

is not related to your first selection, it simply finds every div on the page. Try

$('#panels * div').toggle();

instead

网友答案:

Select propriate divs and operate on them:

$("#panels li div").each(function (i) {
// Do some other things on them here... with this context for the current div
$(this).toggle();
});

EDIT:

the same as

$("#panels li div").toggle();

网友答案:

If you want to hide all the div's inside the ul list then it is just the problem with the selector. You do not need to write the loop to select the elements . Because in jQUery when you write a selector all the elements that satisfy the condition are iterated and selected..

All these three selectors accomplish the same thing..
The first and the second selectors are almost the same. They select all the div's which are under ul.
I prefer the third selector as it will select only the immediate children i.e, li in this case and only hide the div's inside them...