niksmac
niksmac

Reputation: 2782

How can I target a element relative to the clicked element?

Given the HTML structure shown below, I'm hoping that if you click on a p in a ul the div.selected next to that ul will have .css("background", "yellow") performed on it.

<ul>
    <li>
        <p>Hello</p>
        <p>Hello</p>
    </li>
</ul>

<div>Hello Again</div>
<div class="selected">Hello Again</div>
<div><span>And Again</span></div>

<ul>
    <li>
        <p>Hello</p>
        <p>Hello</p>
    </li>
</ul>


<div>Hello Again</div>
<div class="selected">Hello Again</div>
<div><span>And Again</span></div>

So far I've got;

$("p").next("div .selected").css("background", "yellow");

Upvotes: 3

Views: 187

Answers (4)

user133408
user133408

Reputation:

It's better to add css class to separate css from js, like this:

$('div.selected').addClass('className');

Upvotes: 0

Matt
Matt

Reputation: 75317

You'll need:

$('ul').on('click', 'p', function () {
    $(this).closest('ul').nextAll('div.selected:first').css('background', 'yellow');
});

on() was introduced in jQuery 1.7, so if you're using an older version, try;

$('ul p').bind('click', function () {
    $(this).closest('ul').nextAll('div.selected:first').css('background', 'yellow');
});

To add a event handler to a click you need to use an event method. See also the documentation for on(), closest() (to select the first ancestor which matches a selector), nextAll() (which selects the next siblings which matches the selector; as apposed to next() which only considers the next element for selection).

Upvotes: 1

Pavan
Pavan

Reputation: 4329

Why don't you add the below css

.selected{
       bacground-color:yellow;
}

or you could try this

$("p").parents('ul').siblings("div.selected").css("background-color", "Red")

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

$("p").next("div .selected").addClass("selected");

Upvotes: 2

Related Questions