Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding a class within the same div with jquery

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/

like image 949
whatf Avatar asked Dec 21 '22 02:12

whatf


2 Answers

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.

like image 76
gdoron is supporting Monica Avatar answered Jan 10 '23 16:01

gdoron is supporting Monica


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.

like image 41
mu is too short Avatar answered Jan 10 '23 16:01

mu is too short