How to add a class to an element if there are less than two or three on the page.

For example there is:

<div class="block"></div> <div class="block"></div> <div class="block"></div> 

All have a width:

 width: 33.333% 

There are pages on which only two or one block is displayed, it turns out that it does not look very nice. Is there a solution on jQuery that allows you to specify a condition that if there are less than 3 elements, then an additional class is added, containing for example:

 width: 50%; 

Or if there is only one .products element, it is assigned a class containing:

 width: 50%; margin: 0 auto; 

Described the styles for clarity of the problem.

    2 answers 2

     $(function(){ var block_len = $('.block').length; if(block_len == 3) $('.block').addClass('class-name');//если 3 else if(block_len == 2) $('.block').addClass('class-name-50');// если 2 else if(block_len == 1) $('.block').addClass('class-name-50-mg');// если 1 }); 
    • Excellent thank you! - Frontendman

    This is easily solved with CSS and Flex :

     function add(wr){ if(wr.children.length < 9) wr.innerHTML += `<div class='some'>${parseInt(wr.querySelector('.some:last-child').textContent) + 1}</div>`; } function remove(wr){ if(wr.children.length > 1) wr.querySelector('.some:last-child').remove(); } document.addEventListener('DOMContentLoaded', e => { var wrapper = document.querySelector('#wr') document.querySelector('#add').addEventListener('click', function(){add.call(null, wr)}); document.querySelector('#rem').addEventListener('click', function(){remove.call(null, wr)}); }); 
     #wr{ display: flex; flex-wrap: wrap; justify-content: space-around; width: 100%; height: 50px; border: 1px solid red; } .some{ flex-grow: 1; min-width: 10%; border-left: 1px solid gray; } 
     <div id='wr'> <div class='some'>1</div> <div class='some'>2</div> <div class='some'>3</div> </div> <hr /> <input type='button' id='add' value='+' /> | <input type='button' id='rem' value='-' /> 

    JS just for implementing buttons for an example.

    • Thanks, but flex doesn't work for me. - Frontendman
    • Everybody supports him already and for a long time, if you are talking about it. - user207618