Search code examples
jqueryparents

Jquery Find a especific Parent


Using Jquery, I'd like to know how can I take the text (Take this text clicking in button (btnId)) between tag <h4> </h4> when I click the button (btnId)? Bcause i got too much difficult to solve it!

<div class = "class1" id = "class1">
    <div class = "class2" id = "class2">

        <div class = "class4" id = "class4">

            <h4 class = "h_reference" id = "h_reference"> Take this text clicking in button (btnId)</h4>

        </div>

    </div>


    <div class = "class3" id = "class3">
        <div class = "class5" id = "class5">
            <div class = "class6" id = "class6">

            </div>

            <div class = "class7" id = "class7">
                <div class = "class8" id = "class8">    
                    <div class = "class9" id = "class9">

                    </div>
                    <button id="btnId" />
                </div>
            </div>
        </div>
    </div>
</div>

Solution

  • If I'm understanding your question properly, you want to fetch the inner text of a given element on click via jQuery. Here's how:

    $('#btnId').click(function() {
      var txt = $('#h_reference').text();
      //do what you will with txt here
    });
    

    This assigns a click handler to the button via jQuery's $.click function. That handler reads the text of the h4 with id h_reference. From there, you can do what you want with that text.