This is the html content from which I want to select all elements inside report having display block using jQuery
$("#report:visible")
does not work for me.
<div id="report">
<div id="p1" style="display: block;">
<input id="pname1" type="checkbox" name="report1">
<input id="pname2" type="checkbox" name="report2">
</div>
<div id="p2" style="display: none;">
<input id="pname1" type="checkbox" name="report1">
<input id="pname2" type="checkbox" name="report2">
</div>
<div id="p3" style="display: none;">
<input id="pname1" type="checkbox" name="report1">
<input id="pname2" type="checkbox" name="report2">
</div>
<div id="p4" style="display: block;">
<input id="pname3" type="checkbox" name="report1">
<input id="pname4" type="checkbox" name="report2">
</div>
</div>
Maybe you can use this piece of jQuery :
$("#report div:visible").each(function() {
console.log($(this).attr('id'));
});
Or this one :) ?
$("#report div:visible");
$("#report > :visible")
This will select the direct children of #report
that are visible. Without the space you're selecting #report
itself if it's visible. (Without the >
it'd target also the inputs.)
You could use:
$("[style='display: block;']");
but I wouldn't, I'd add a class as well to hook onto.
You cannot directly select elements in CSS using a property value itself. You can however select by class. The best solution would be to use a class to assign display: block
(such as a visible
class) and then to select based on its presence or lack thereof.
The other way to do this is to select using the entire value of the style
element. But the problem with this is that if you add other inline styles that selector will no longer work. You could then get into regex parsing the style attribute but in my opinion applying a visible
or hidden
class is far easier and will perform significantly better.
Note that another advantage of using the visible
or hidden
class is that you can turn it on and off with JavaScript very easily:
document.getElementById("id").classList.toggle("hidden");
This may help you with several selectors CSS Selectors.
As for your requirement, You can use this to select all div
with display:block
under the #report
.
$('#report div[style*=display:block]')
Why not just
$('#report div:visible');
if markup stays like that it will work. If not just add a class to the report entries like 'entry' then do
$('#report .entry:visible');
This should work:
$("#report *").filter(function(){
$(this).css("display") === "block";
});
The * selects all elements within the #report. You're then filtering them to those with CSS property set to block.
Use :visible
in place of [style*="display:block"]
as it will work in all browsers including IE. [style*="display:block"]
will not work in IE.