Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select first element that has a certain class after this

Here is my fiddle: http://jsfiddle.net/jamesbrighton/wxWgG/4/

HTML:

<div>
    <p class="click">Click 1</p>
    <p>This should be ignored</p>
    <p>This should be ignored</p>
    <p>This should be ignored</p>
</div>

<div>
    <p class="target">Target 1</p>
</div>
<div>
    <p class="target">Target 2</p>
</div>


<div>
    <p class="click">Click 2</p>
    <p>This should be ignored</p>
    <p>This should be ignored</p>
    <p>This should be ignored</p>
</div>

<div>
    <p class="target">Target 3</p>
</div>
<div>
    <p class="target">Target 4</p>
</div>

jQuery:

$('.click').click(function() {
   $(this).nextAll('.target').css('color','red');
});​

I need it so when you click a p.click, the next p.target turns red.

So if you click on 'Click 1' then 'Target 1' turns red. If you click on 'Click 2' then 'Target 3' turns red.

As well as .find I've tried .closest and from the jQuery documentation it seems to me like it should work. As you can see from the HTML, .target is not a child of .click, in case that makes a difference.

like image 645
Evanss Avatar asked Mar 22 '12 16:03

Evanss


People also ask

How to select first class in jQuery?

The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the first element in a group (like in the example above).

How to select element with class and ID in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

How to select a single element using jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.


2 Answers

Here is another approach, although I don't know how performant .index() is in this case. This also assumes that there are never two consecutive .click elements (or phrased differently: There is always at least one .target element between two .click elements):

var $elements = $('.click, .target');

$('.click').click(function() {
   $elements.eq($elements.index(this) + 1).css('color','red');
});​

DEMO

This works because the elements are selected in the order they appear in the document.

like image 60
Felix Kling Avatar answered Sep 19 '22 16:09

Felix Kling


Are you looking for this?

$('.click').click(function() {
    $(".target", $(this).parent().next()).css('color','red');
});

Updated Fiddle

like image 44
amit_g Avatar answered Sep 19 '22 16:09

amit_g