Is this what you are looking for? (Find the target element through the while loop)
$('.click').on('click', function() { var coc = $(this); while( !coc.prev().is( '.change-on-click' ) ) { coc = coc.parent(); } coc.prev().css('color','red'); });
$('.click').on('click', function() { var coc = $(this); while( !coc.prev().is( '.change-on-click' ) ) { coc = coc.parent(); } coc.prev().css('color','red'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div> <div> <p class="change-on-click">A</p> <p class="click">Click on this will change A</p> </div> </div> <div> <div> <p class="change-on-click">B</p> <div> <p class="click">Click on this will change B</p> </div> </div> </div> <div> <div> <p class="change-on-click">C</p> <div> <div> <p class="click">Click on this will change C</p> </div> </div> </div> </div>
OR (Using jQuery Plugin)
$('p.click').on('click', function(){ $(this).changeOnClick(); }); $.fn.changeOnClick = function() { return this.each(function() { var near = $(this); while( !near.prev().is('.change-on-click') ) { near = near.parent(); } near.prev().css('color','red'); }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div> <div> <p class="change-on-click">A</p> <p class="click">Click on this will change A</p> </div> </div> <div> <div> <p class="change-on-click">B</p> <div> <p class="click">Click on this will change B</p> </div> </div> </div> <div> <div> <p class="change-on-click">C</p> <div> <div> <p class="click">Click on this will change C</p> </div> </div> </div> </div>
UPDATE
The next version should work for cases when the target element is before or after the element with a click:
$('.click').on('click', function() { var coc = $(this); while( !coc.prev().is( '.change-on-click' ) && !coc.next().is( '.change-on-click' ) ) { coc = coc.parent(); } coc.prev().add( coc.next() ).filter( '.change-on-click' ).css('color','red'); });
Demo
source share