Ben Ben - 1 month ago 7
jQuery Question

How to select current element by class inside in jQuery?

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

Answer

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'); }
    });
});
Comments