After reading your clarification comment, you have the option to utilize the siblings
method in order to access the p
elements that are siblings of the a
elements. Assuming they have a common parent element, this code should suffice:
$('a.text_blue').click(function() {
$(this).siblings('p').removeAttr('class').addClass('blue_text');
});
If for some reason they are not actually siblings due to changes in the markup structure, you can use the parent
method to navigate up to the div
, and then employ the find
method to target the descendant p
elements:
$('a.text_blue').click(function() {
$(this).parent().find('p').removeAttr('class').addClass('blue_text');
});
In addition, there's an opportunity to refactor your code so that it doesn't require separate event handlers for each individual a
element. One approach could be like this:
<a href="#" data-class="blue-text"></a>
Then, delegate the event handling as follows:
$(".color_changer").on("click", "a", function() {
$(this).parent().find("p").removeAttr("class").addClass($(this).data("class"));
});
Update
Now that you've shared a link to your code snippet, I'm able to provide a more specific solution! The p
element you're aiming for is actually a sibling of the containing div
:
$('a.text_blue').click(function() {
$(this).parent().siblings('p').removeAttr('class').addClass('blue_text');
});
Furthermore, with jQuery 1.6 at your disposal, you still have the advantage of event delegation using the delegate
method:
$(".color_changer").delegate("a", "click", function() {
$(this).parent().siblings('p').removeAttr("class").addClass($(this).data("class"));
});