0

I have a loop that dynamically populates information.

<div class="main">

 <div class="more">
    more
 </div>
 <span></span>
   ....
 <div class="more">
    more
 </div>
 <span></span>

</div>

on clicking specific div I am calling "ajax" - on success I want to override that specific div's content and next span with some content.

   $(document).on("click", ".more", function (event) {
            $.ajax({
                url: '..',
                datatype: 'application/json',
                success: function (data) {
                    $(".more",this).html("Update Dev"); //update div
                    $(".more",this).find('span:first').text("Update Span"); //update span 
                },
                error: function () { alert('something bad happened'); }
            });
        });

How would I access the element that was clicked.

Thanks

2

1 Answer 1

2

You can use $(this) inside click handler to get the clicked button. Make sure to capture it in click handler, not in AJAX callback:

$(document).on("click", ".more", function (event) {
    var clickedDiv = $(this);  // <- capture clicked div to variable

    $.ajax({
        url: '..',
        datatype: 'application/json',
        success: function (data) {
            // use captured div to set the contents
            clickedDiv.html("Update Dev");
            // use captured div and function next() to get the span element
            clickedDiv.next('span').html("Updated span");  // then update span
        },
        error: function () { alert('something bad happened'); }
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

thanks so much for the explanation. The span would not update. I modified by ` clickedDiv.next('span').html("Updated span");` and it worked.
@Ben Yes, you are right - I copied selector from the div and I did not notice that span does not have more class. I updated the answer
I was wondering is it easy to add .animate for example when div is changing? I know I didn't specify in my question, is it something simple to add?

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.