I'm trying to target a specific parent of an element and then add a class to it with jQuery. Example:
$('.disable-link').click(function(e) {
$(this).hide();
$(this).parents('.item').find('.title').addClass('disabled');
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
<div class="title">Thing 1</div>
</div>
<div>
<a class="disable-link" href="#">Click to Disable Thing 1</a>
</div>
<div class="item">
<div class="title">Thing 2</div>
</div>
<div>
<a class="disable-link" href="#">Click to Disable Thing 2</a>
</div>
<div class="item">
<div class="title">Thing 3</div>
</div>
<div>
<a class="disable-link" href="#">Click to Disable Thing 3</a>
</div>
I thought that by using .parents('.item') it would go all the way up the chain to that specific item class with this and target that specific one, but for some reason it's not.
I've tried using parent().parent().find('.title') but that ends up adding the disabled class to all of the titles and not just the one.
I have a feeling that it something simple, but I can't wrap my head around the specific inheritance.
The elements with class .item are not a parents of .disable-link elements so you should target the parent div first then get the previous .item using the .prev() method like:
$('.disable-link').click(function(e) {
$(this).hide();
$(this).parents('div').prev('.item').find('.title').addClass('disabled');
e.preventDefault();
});
Hope this helps.
$('.disable-link').click(function(e) {
e.preventDefault();
$(this).hide();
$(this).parents('div').prev('.item').find('.title').addClass('disabled');
});
.disabled{
background-color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
<div class="title">Thing 1</div>
</div>
<div>
<a class="disable-link" href="#">Click to Disable Thing 1</a>
</div>
<div class="item">
<div class="title">Thing 2</div>
</div>
<div>
<a class="disable-link" href="#">Click to Disable Thing 2</a>
</div>
<div class="item">
<div class="title">Thing 3</div>
</div>
<div>
<a class="disable-link" href="#">Click to Disable Thing 3</a>
</div>