Home > Software design >  Inject HTML using jQuery closest() and Ajax
Inject HTML using jQuery closest() and Ajax

Time:10-04

I have a list in which each item can display its content by injecting it with Ajax.

(function($) {
    $(document).ready(function() {

        $('.show-content').click(function() {
            
            var post_id = $(this).closest('article').attr('data-post-id');

            // ↓ Works. Target the .content <div> in the single <li>.
            $(this).closest('li').find('.content').prepend('<div class="loader">Loading...</div>'); 
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    'action': 'load_loop_content',
                    'post_id': post_id
                }
            }).done(function(response) {

                // ↓ Does not work, the button stay displayed.
                $(this).hide(); // Hide Button
                // ↓ Work, but hide the button in all <li>.
                // $('.show-content').hide(); // Hide Button

                // ↓ Works only using $('.content').html(response) and has been injected into all <li>.
                $(this).closest('li').find('.loader').hide(); // Hide Loader

                // ↓ Does not work, nothing happens and the message "Loading ..." is still displayed.
                $(this).closest('li').find('.content').html(response); // Inject Content
                // ↓ Works, but inject the post content in all <li>.
                // $('.content').html(response);

            });

        });
        
    });
})(jQuery);

But using closest(), it doesn't work anymore. I put the details in the comments of the code.

Any ideas where the problem is coming from?

CodePudding user response:

Just store your content to a const and use it afterwards

(function($) {
$(document).ready(function() {

    $('.show-content').click(function() {

        const myButton = $(this);
        var post_id = myButton.closest('article').attr('data-post-id');

        // ↓ Works. Target the .content <div> in the single <li>.
        const myContent = myButton.closest('li').find('.content');
        myContent.prepend('<div class="loader">Loading...</div>'); 
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                'action': 'load_loop_content',
                'post_id': post_id
            }
        }).done(function(response) {

            myButton.hide(); // Hide Button
            myContent.html(response);

        });

    });
    
});
})(jQuery);
  • Related