0

DEMO

How to update B text when C is clicked?

HTML

<div class="A">
    <div><span class="B">TEXT</span></div>
    <div>
        <div id="C" onclick="tx(this.id);">CLICK ME</div>
    </div>
</div>

JQUERY

function tx (e){
    $('#' + e).closest('.A').children('.B').text('SUCCESS');
}

I cant understand why the above jquery does not work.

It should find nearest parent then child.

3 Answers 3

4

Since you're using jQuery anyway, assign your event handlers that way instead of using "onclick" attributes:

$("body").on("click", "#C", function() {
    $(this).closest('.A').find('.B').text('SUCCESS');
});

HTML:

<div class="A">
    <div><span class="B">TEXT</span></div>
    <div>
        <div id="C">CLICK ME</div>
    </div>
</div>

Note that as set up, your fiddle won't work because the "tx" function is configured (via jsfiddle settings) to be inside a "load" handler, and is therefore not a global symbol.

Fixed fiddle link.

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

Comments

1

You have many parents, so this can get a little confusing. Make sure you use .children() twice.

function tx(e) {
  $('#' + e).parents('.A').children().children('.B').text('SUCCESS');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="A">
  <div><span class="B">TEXT</span>
  </div>
  <div>
    <div id="C" onclick="tx(this.id);">CLICK ME</div>
  </div>
</div>

1 Comment

I think .closest() really is the better choice here, because it is guaranteed to return a jQuery object with either zero or one members.
0

Is there any reason you are calling the click event inline? I would rather do all the events on DOM ready and then simply do something like: http://jsfiddle.net/t668p52p/3/

$('#C').on('click', function() {
    $(this).parents('.A').find('.B').text('SUCCESS');
});

1 Comment

Yes it is just a mistake in my fiddle. fixed now.

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.