Search code examples
jqueryhtmltextparent

Jquery Selecting Previous Element After Click


<div class="container">
 <div class="well">
  <h2>Hurry Up!</h2>
   <ul>
    <li>
     <a onclick="clicked()"></a>
    </li>
    <li>
     <a onclick="clicked()"></a>
    </li>
   </ul>
  </div>
</div>

Above is a sample of my html syntax. What I want to achieve is when "a" tag is clicked, I want to find the text of the "h2" element.

For example, when the "a" tag is clicked, the text "Hurry Up!" of h2 should be shown in console.

I tried this but its not working:

function clicked(){
        var title = $(this).find('h2').text();
        console.log(title);
}

And also this :

function clicked(){
        var title = $(this).parentsUntil('.container').find('h2').text();
        console.log(title);
}

In console, nothing appears, only a blank line.

What I want to add is i have this same syntax many times. So the h2 text should be of the container in which it was clicked, because of which I am trying it through 'this'.


Solution

  • Try this

    function clicked(element){
            var title = $(element).closest('div').find('h2').html();
            console.log(title);
            alert(title);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container">
     <div class="well">
      <h2>Hurry Up!</h2>
       <ul>
        <li>
         <a onclick="clicked(this)" href="#">Click 1</a>
        </li>
        <li>
         <a onclick="clicked(this)" href="#"> Click 2</a>
        </li>
       </ul>
      </div>
    </div>