Reputation: 366
I'm having difficulty understanding why a particular selector isn't working for me. Admittedly I'm a bit of a JQuery newbie.
This correctly selects the first div.editbox on the page and colors it yellow:
$('div.editbox:first').css("background-color","yellow");
However, this if ... is
construct makes the highlighted border appear for each box as it is moused-over.
$('div.editbox').bind('mouseover', function(e) {
if ($(this).is('div.editbox:first')) {$(this).css("border", "1px solid red");}
});
I have tried variations such as '.editbox :first', '.editbox div:first', etc.
Essentially, I want to be able to reliably test whether this is the first or last element of with the class name.
Thanks!
Edit: here's the HTML I'm using:
<body>
<div class="container">
<p></p>
<div class="editbox" id="box1">Foo</div>
<div class="editbox" id="box2">Bar</div>
<div class="editbox" id="box3">Baz</div>
<div class="responsebox" id="rbox"></div>
</div>
</body>
This is just a proof-of-concept page; the actual page will of course be much more complex. Again: what I want is to reliably detect if I am in the first or last "div.editbox". A workaround I used is:
$('div.editbox:last').addClass("lasteditbox");
Then test for if ($(this).is(".lasteditbox"))
which works, but it seems clumsy and I'm trying to learn the proper way to do this with JQuery.
Upvotes: 2
Views: 302
Reputation: 51488
UPDATE: This works for the first element.
$('div.editbox').bind('mouseover', function(e) {
if ($("div.editBox").index(this) == 0) {
$(this).css("border", "1px solid red");
}
});
And for the last element, this selector works:
if($("div.editBox").index(this) == ($("div.editBox").length-1)){
$(this).css("color","red");
}
Upvotes: 2
Reputation: 30364
If you want the mouseover on just the first occurence of the class editbox inside div
$('div.editbox:first').mouseover(function() {
$(this).css("border", "1px solid red");
});
Edit
$('div.editbox').mouseover(function() {
$(this).css("border", "1px solid yellow");
}).filter(':first').mouseover(function(){
$(this).css("border", "1px solid red");
}).filter(':last').mouseover(function(){
$(this).css("border", "1px solid blue");
})
Upvotes: 2
Reputation:
$('div.editbox').mouseover(function() {
//change the css for all the elements
$(this).css("background-color", "yellow");
})
.filter(':first,:last').mouseover(function(){
//execlude the first and the last
$(this).css("background-color", "Blue");
})
Upvotes: 0
Reputation: 1209
have u tried
if ($(this).is(':first')) {$(this).css("border", "1px solid red");}
Upvotes: 0