This question is a party duplicate of an answer in jQuery count div that has display:block. I changed getElementsByTagName
to getElementsByClassName
and block
to flex
in the -if- statement.
Because I need the following functionality: Count the divs that are set with style display: flex in a separate stylesheet, so not inline, and then output the number count in a div; when the count is “0” output should be 0 in text, else the correct number of counted divs.
I am a beginner in Javascript and don’t know how I should continue.
Thank you.
$(function(){
var allElems = document.getElementsByClassName('displayflex');
var count = 0;
for (var i = 0; i < allElems.length; i++)
{
var thisElem = allElems[i];
if (thisElem.style.display == 'flex') count++;
}
alert(count);
});
.displayflex {
display: flex;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<div class="displayflex"></div>
<div class="displayflex"></div>
<div class="displayflex"></div>
<div></div>
</div>
<div id="outputnumber"></div>
3
Answers
The problem is that the
style
attribute only reads inline styles. You will need to look at the computed styles of each element to see styles applied via CSS.Here using the appropriate
const
andlet
declarations for variables, afor...of
loop for brevity, and updating thetextContent
of the relevant div with the result.You need computed style like below