user1324762
user1324762

Reputation: 805

jquery this selector after clicked element removed

I want to empty content of div with class dialogBody and then append returned ajax response. See the code below please. The problem I have is .html(response) doesn't do anything because clicked element is removed. How can I carry over the target element which is $this.closest('.dialogBody') after clicked element was removed?

<div class="dialogBody">
  <p>Some content<a href="/question/33" class="ajaxReplace">Click to show question</a></p>
</div>
<script>
$(".ajaxReplace").live("click", function(e){
  e.preventDefault();
  var $this = $(this);
  $this.closest('.dialogBody').empty();          
  ajaxUrl = $(this).attr("href")+"?ajax=1";
  $.ajax({ 
    type: "POST",
    url: ajaxUrl,
    success: function(response){          
      $this.closest('.dialogBody').html(response);  
      console.log(response);
    }
  })                 
});   
</script>

Upvotes: 0

Views: 143

Answers (2)

nnnnnn
nnnnnn

Reputation: 150040

Save a reference to the element you need instead of saving a reference to the element that will be removed:

$(".ajaxReplace").live("click", function(e){
  e.preventDefault();
  var ajaxUrl = $(this).attr("href")+"?ajax=1",
      $thisDialog = $(this).closest('.dialogBody').empty();          
  $.ajax({ 
    type: "POST",
    url: ajaxUrl,
    success: function(response){          
      $thisDialog.html(response);  
      console.log(response);
    }
  })                 
});  

You'd also need to move the ajaxUrl assignment to before you remove the this element.

Upvotes: 2

Joseph Marikle
Joseph Marikle

Reputation: 78530

Assign it to a variable:

$(".ajaxReplace").live("click", function(e){
  e.preventDefault();
  var $this = $(this);
  var $dBody = $this.closest('.dialogBody').empty();   // <------       
  ajaxUrl = $(this).attr("href")+"?ajax=1";
  $.ajax({ 
    type: "POST",
    url: ajaxUrl,
    success: function(response){          
      $dBody.html(response);  // <------
      console.log(response);
    }
  })                 
});  

Upvotes: 4

Related Questions