Chung
Chung

Reputation: 1073

how to "chain" selector together and apply the same function in jQuery

Maybe the title didn't really state what my question is.

<ul>
    <li>A</li>
    <li>B</li>
    <li class="test">C</li>
    <li>D</li>
</ul>

what I am trying to do is apply background colour to the adjacent siblings of an element with class "test", and itself as well, totally three of them will have a background colour. so i have to do the following.

    $('ul li.test').each(function(){
        $(this).prev().css('background','red');
        $(this).css('background','red');
        $(this).next().css('background','red');
    });

which i reckon it is a pretty ugly coding. Is there a way to do something like $(prev, this, next).somefunction() thank you

Upvotes: 4

Views: 148

Answers (5)

nd_macias
nd_macias

Reputation: 812

Ok, I think I would maybe try to join some css practice with jQuery and do it this way:

CSS

.test,
.test + li {
  background: red;
}

jQuery

$('.test').prev().css('background','red');

But I wonder myself if there's cleaner solution. :)

Upvotes: 0

Blender
Blender

Reputation: 298206

You can use .add() to add elements to the set of matched elements:

$(this).add($(this).prev()).add($(this).next()).css('background','red');

Or with .addBack() (.andSelf() for jQuery versions before 1.8):

$(this).prev().addBack().next().addBack().css('background','red');

Upvotes: 2

Zach Lesperance
Zach Lesperance

Reputation: 347

You can compact two of them together using the Next Adjacent Selector

$(".test, .test + li").css("background-color","#F00");

I also tried tried $("li + .test") as well, but that wasn't working for me

Edit:

$("li + .test") does work, but it selects the .test element. There doesn't seem to be a previous adjacent selector though

Hope this helps

Upvotes: 0

Ricardo Souza
Ricardo Souza

Reputation: 16456

You can create a variable to cache the selection and apply the styling to it.

var $this = $(this);
var elements = $this;
elements.add($this.prev());
elements.add($this.next());

elements.css('background','red');

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

use .end()

$(this).prev().css('background','red')
       .end().css('background','red')
       .next().css('background','red');

Upvotes: 1

Related Questions