How do I affect only the first matching element with a JQuery selector
Demo of applying changes to the first element only OR at a specific element
by Brian Layman
HTML
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div id="stop">Stop here</div>
<div></div>
<div></div>
<div></div>
<br clear="all"/>
<button id="button1">Hard: Iterate to change color ( Click a second time to change more )</button>
<button id="button2">Easy: Use selector change color of first item</button>
CSS
div {
width: 40px;
height: 40px;
margin: 5px;
float: left;
border: 2px blue solid;
text-align: center;
}
button {
clear: both;
}
JavaScript
// The Hard Way
$( "#button1" ).click(function() {
$( "div" ).each(function( index, element ) {
var firstRun = (index == 0) && ($( element ).css( "backgroundColor") !== "rgb(255, 255, 0)" );
$( element ).css( "backgroundColor", "#ffff00" );
// return false; // Uncomment to always only affect 1st matching element
if ( firstRun || $( this ).is( "#stop" ) ) {
$( "span" ).text( "Stopped at div index #" + index );
return false; // Return false always exits the each loop. Use without a condition to get the first element only.
}
});
});
// The Easy Way
$( "#button2" ).click(function() {
$( "div:first" ).css( "backgroundColor", "#0000ff" );
});