Search code examples
jqueryhtmlclassparent

JQuery get the class within a parent


I have literally spent hours with JQuery trying to extract a piece of text from a class, in the code below you can see that when the reply button is clicked JQuery looks for a class called name in order to extract a piece of text which in this instance is bob green.

I am always one to research these type of things but since none of this code works I am stuck, in the JQuery code below you can see that I have tried different ways in extracting the text.

If anyone could help me fix this problem I would be more than grateful.

<div class='replyContainer'>
    <div class='image'></div>
    <span>
        <div class='close' title='Close'></div>
        <b><font class='name'>bob green</font></b>
        test message
    </span>
    <div class='bubble-triangle-border'></div>
    <div class='bubble-triangle'></div>
    <div class='info'> 
        <div class='reply'></div>
    </div>
</div>


$(".replyContainer .reply").live('click',function(){    
    var replyName = "@" + $(this).parent().parent(".name").text();
});


$(".replyContainer .reply").live('click',function(){    
    var replyName = "@" + $(this).parent().parent().closest(".name").text();
});

$(".replyContainer .reply").live('click',function(){    
    var replyName = "@" + $(this).parent().parent("span font.name").text();
});

Solution

  •  $(".replyContainer .reply").live("click", function() { 
          var replyName = "@" + $(this).closest(".replyContainer").find(".name").text()
     })
    

    A few other things:

    1. jQuery.live() is considered deprecated (see: http://api.jquery.com/live/), you should use .delegate() or .on() instead.
    2. You should totally not use the <font> tag but use CSS!
    3. closest() goes up the DOM parents and their parents, and find() goes downward and looks at children!