简体   繁体   中英

How to retrieve .length of numerous elements with a particular class using jQuery?

Yo guys, The problem is as follows: on the website I'm currently working there are numerous boxes, each of which has some little area in the corner that is supposed to count users when the website goes live. Thus, just for the test I've used a with an id in my markup for accommodating the number:

<span id="usercount">612</span>

with the following lines of simple jQuery:

var users = $('#usercount').text().length;

if (users >= 4) {
    $('#usercount').css('font-size','12px');
    $('#usercount').css('margin-left','7px');
}

As you see, if a number has 4 or more symbols it gets smaller and aligned properly inside this area. But since there should be numerous boxes on the website, I've changed id="usercount" to a class="usercount" and it's not working any longer. I understand that there should be some loop for retrieving the same piece of data from every element with the class of "usercount" but I can't figure out how to put it down competently with a proper syntax. I realize it's a simple operation, but I'm new to JS and would appreciate your assistance. Thanks a lot!

You can use the filter method:

$('.usercount').filter(function() {
   return $(this).text().length >= 4;
}).css({
    'font-size': '12px', 
    'margin-left': '7px'
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM