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.
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).
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.
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.
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.
Are you looking for this?
$('.click').click(function() {
$(".target", $(this).parent().next()).css('color','red');
});
Updated Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With