Jaycel Cunanan
Jaycel Cunanan

Reputation: 23

How to find an element outside div in jquery

When I click the button it print a text to the nearest class "print". Can anybody help me please.

HTML :

<div class ="row">
  <div id = "div1">
     <div class ="col-md-12">
         <button class ="button">print</button>
     </div>
  </div>
  <div id ="div2">
     <div class ="print">
     </div>
  </div>
</div>
<div class ="row">
  <div id = "div1">
     <div class ="col-md-12">
         <button class ="button">print</button>
     </div>
  </div>
  <div id ="div2">
     <div class ="print">
     </div>
  </div>
</div>

Upvotes: 0

Views: 3597

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could use closest() or parents() to go up to the parent div with class row then find the element with class print using find() method and get finally get the text using text() :

$("button").on('click', function(e){
   console.log( $(this).closest(".row").find(".print").text() );
   //Or
   console.log( $(this).parents(".row").find(".print").text() );
})

Hope this helps.

$("button").on('click', function(e){
  console.log( $(this).parents(".row").find(".print").text() );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class ="row">
  <div id = "div1">
    <div class ="col-md-12">
      <button class ="button">print</button>
    </div>
  </div>
  <div id ="div2">
    <div class ="print">Print div 1 content</div>
  </div>
</div>
<div class ="row">
  <div id = "div1">
    <div class ="col-md-12">
      <button class ="button">print</button>
    </div>
  </div>
  <div id ="div2">
    <div class ="print">Print div 2 content</div>
  </div>
</div>

Upvotes: 0

Paulo Lima
Paulo Lima

Reputation: 1238

I think that your answer is this:

$("button").click(function(e){
  var text = $(e.target).closest(".row").find(".print").text();

  alert(text)
})

Upvotes: 1

Related Questions