简体   繁体   中英

Run each() but only apply on the first result

How do I turn the first p to red?

I'm using each() because I need to search for all the P's. But I only want the code to work on the first result only, "exit" after that or something like that.

How can I do that with jQuery?

PS: This is a simple example, the code is more complex than that, so please don't suggest something like $('p').eq(0) or a CSS way... I need to do this with jQuery running the each method.

Thanks.

http://jsfiddle.net/ybr2qh46/

<p>name 1</p>
<p>name 2</p>
<p>name 3</p>

(function($){
    $('p').each( function(){
    $(this).css( 'color', 'red');
  });
})(jQuery)

You can return false in order to stop the loop from continuing to the next element:

 (function($){ $('p').each( function(){ $(this).css( 'color', 'red'); return false; }); })(jQuery) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>name 1</p> <p>name 2</p> <p>name 3</p> 

Another option - if you want the loop to continue (but still want to change only the first element) - you can check if that element is the first one:

 (function($){ $('p').each( function(i) { if (i == 0) { $(this).css( 'color', 'red'); } }); })(jQuery) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>name 1</p> <p>name 2</p> <p>name 3</p> 

You can try to use .first() method. It's used to select first selector if there is 1 or more than 1 selectors.

 $('p').first().css( 'color', 'red'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>name 1</p> <p>name 2</p> <p>name 3</p> 


Another option ( must use each method ):

 var item = Array.from($('p').each(function (){}))[0]; $(item).css('color', 'red'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>name 1</p> <p>name 2</p> <p>name 3</p> 

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