You need to add a class to the <div> after comparing its contents with the specified string:

 if ($('#orders .order :last-child').text() === 'Z' ) { console.log('green'); $(this).addClass('green'); //тут проблема } 
 .order { display: inline-block; padding: 5px; } .green { background-color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='orders'> <div class='order'> <div class='b1'>X</div> <div class='b2'>Y</div> <div class='b3'>Z</div> </div> </div> 

  • Do not insert keywords into the title of the question if they do not have a direct relationship to it: there are tags for this. - Alexey Ukolov

1 answer 1

The fact is that $ (this) at the time of execution refers not to the desired div, because it is not an event handler to which jQuery automatically binds the context, but simply a check. Therefore, you need to save the found element to a variable and work with it:

 var $myEl = $('#orders .order :last-child'); if ($myEl.text() === 'Z') { $myEl.addClass('green'); } 
  • And if there are several such divs - Oleg Ivanov
  • So, you need to use .each () and that's where $ (this) will refer to the element being processed. jsfiddle.net/alexey_m_ukolov/7n839hc3 - Alexey Ukolov
  • Alexey, could you give an example with each () to cite - Oleg Ivanov