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 ></div>
<div ></div>
<div ></div>
<div></div>
</div>
<div id="outputnumber"></div>
CodePudding user response:
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
and let
declarations for variables, a for...of
loop for brevity, and updating the textContent
of the relevant div with the result.
$(function () {
const allElems = document.getElementsByClassName('displayflex');
let count = 0;
for (const elem of allElems) {
const compStyles = window.getComputedStyle(elem);
if (compStyles.getPropertyValue('display') === 'flex') {
count ;
}
}
document.getElementById('outputnumber').textContent = count;
});
.displayflex {
display: flex;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<div ></div>
<div ></div>
<div ></div>
<div></div>
</div>
<div id="outputnumber"></div>