I want to find a class corresponding to another class within the same div.
HTML structure:
<div class="main">
<div class="party">
<a href="#"><img id="1001" class="vote" src="http://img2.jpg"></a>
<p class="votenums"> 20 votes.</p>
</div>
<div class="party">
<a href="#"><img id="1001" class="vote" src="http://imgtwo2.jpg"></a>
<p class="votenums"> 30 votes.</p>
</div>
jQuery code is:
$(function() {
$(".vote").live("click", function(e) {
e.preventDefault();
$(this).find(".votenums").text("changed text");
});
});
When I click img with class vote I want to edit the class votenums, corresponding to the same div.
meaning, the desired behavior is, when the image is clicked the text should change.
fiddle is here: http://jsfiddle.net/85vMX/1/
find searches down, and .votenums isn't a descendant of .vote you should traverse up to the div and then find the descendant .votenums
$(function() {
$(".vote").live("click", function(e) {
e.preventDefault();
$(this).closest('div').find(".votenums").text("changed text");
});
});
If the div you want will always has class=party you can search by it:$(this).closest('.party').find(".votenums").text("changed text");
Class selector is better than element selector
JSFiddle DEMO
find:
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
closest:
Description: Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
An easy and robust approach is to go back up to .party using closest and then come back down using find:
$(".vote").live("click", function(e) {
e.preventDefault();
$(this).closest('.party').find('.votenums').text("changed text");
});
That lets you change the internal arrangement of .party without breaking your jQuery.
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