Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a class to first div using jQuery

How to add a class to first div using jQuery.

I Tried following code but doesn't work for me. maybe I'm missing something.

<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script>
$('.item')
    .eq(0).addClass('first').end()
    .eq(-1).addClass('last').end();
</script>
<style type="text/css">
.first, .last{
background-color:#0099FF;
}
</style>
</head>
<body>
<div class="item">aaa</div>
<div class="item">bbb</div>
<div class="item">ccc</div>
<div class="item">ddd</div>
<div class="item">eee</div>
</body>
</html>

Edit: Thanks to everyone, is there anyway to add a class to rest of DIVs?

like image 385
Zim3r Avatar asked Dec 07 '25 08:12

Zim3r


2 Answers

You are executing the code before the markup is ready. Wrap the code in

// document ready short-style
$(function() {

});
like image 130
Peter Pajchl Avatar answered Dec 08 '25 21:12

Peter Pajchl


try

$(document).ready(function() {
  $('.item:first-child').addClass('first');
});
like image 36
Andy Avatar answered Dec 08 '25 22:12

Andy