2

let say i have this div

<div id='parent'>
  <button id='button'></button>
  <div id='child'>
     <div id='grandchild' class='lookAtMe'>
          Some JSON text
     </div>
  </div>
</div>

I wanted to give the #button an on click event that returned the text at #lookAtMe div, specific to the div whom it shares parent/grandparent (in this case, the #parent div)

I tried using:

 $("#button").on("click",function(){
     var ReturnedText = $(this).parent(".lookAtMe").text();
     console.log(RetrunedText);
 });

But the console log would retruned (empty string).

Where did i do wrong? please help. Thankyou very much.

2
  • 1
    The button doesn't have a parent with class lookAtMe, it has a div with id parent as it's parent. Try $(this).parent().find('.lookAtMe').text(); Commented Feb 7, 2018 at 16:42
  • You don't even need parent... $(this).next().find('.lookAtMe').text() Commented Feb 7, 2018 at 16:45

1 Answer 1

4

Because there is n o parent with that class. You need find().

Actually you need to write

 var ReturnedText = $(this).parent().find(".lookAtMe").text();

 $("#button").on("click",function(){
     var ReturnedText = $(this).parent().find(".lookAtMe").text();
     console.log(ReturnedText);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
  <button id='button'></button>
  <div id='child'>
     <div id='grandchild' class='lookAtMe'>
          Some JSON text
     </div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Ah yes i see, seems like i have miss understanding. I tough the parent() arguments used to select something amon the parent's childern, so it actually used to specify the parents that we need to select. I see now. Thank you. I've tried the code and it worked very well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.