Tell me how to check the width of bar, and if for example it is less than the required value, add a class to this element and leave the rest as is. Tried through $ (this) did not work.

<div class='wrp'> <div class='bar' style='width: 1%'> </div> </div> <div class='wrp'> <div class='bar' style='width: 19%'> </div> </div> <div class='wrp'> <div class='bar' style='width: 54%'> </div> </div> var bar = $(this).closest('.wrp').find('.bar').width(); if(bar > 20) { bar.addClass('reverse'); } 

    2 answers 2

    You specify the width of the elements in percent. But at calculations js will operate with pixels. And the comparison will be only in pixels. In addition, we must understand, from what width of what object do we take a percentage? For example, take the viewport width.

     let $bar = $('.bar'), windowWidth = $(window).width(), prstg = 20; $bar.each(function() { console.log($(this).width()); if ($(this).width() < (windowWidth * prstg)) { $(this).addClass('reverse'); } }); 
     .bar{height:50px;border:1px solid #000} 
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='wrp'><div class='bar' style='width: 1%'></div></div> <div class='wrp'><div class='bar' style='width: 19%'></div></div> <div class='wrp'><div class='bar' style='width: 54%'></div></div> 

     // достаем все элементы .bar var allBars = $('.bar'); // Пробегаемся циклом по ним и проверяем ширину allBars.each(function() { let w = $(this).width(); if (w > 20) $(this).addClass('red'); else $(this).addClass('green'); console.log(w); }); 
     .bar { height: 10px; } .red { background-color: red; } .green { background-color: green; } 
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='wrp'> <div class='bar' style='width: 1%'> </div> </div> <div class='wrp'> <div class='bar' style='width: 19%'> </div> </div> <div class='wrp'> <div class='bar' style='width: 54%'> </div> </div> 

    Jquery.each