Use jQuery's .load() to load page fragments but only get contents of selector

StackOverflow https://stackoverflow.com/questions/18195087

  •  24-06-2022
  •  | 
  •  

سؤال

I am using jQuery's .load() page fragments method to reload a piece of my page:

$("#submit").click(function() {
    $("#box").load('/ajax/box/ #box');
});

It works, however this is causing an error because after the contents is loaded. Since this function essentially uses .innerHTML it is replacing the code on the inside of my div. The HTML result looks like:

<div id="box">
    <div id="box">
        <!-- this is my page -->
    </div>
</div>

I have tried using .parent() but removes all other divs in the parent.

$("#submit").click(function() {
    $("#box").parent().load('/ajax/box/ #box');
});

Essentially this is what I am trying to do (I know the code below is invalid, but that represents what I am trying to accomplish):

$("#submit").click(function() {
    $("#box").load('/ajax/box/ $('#box').html()');
});

Is there a way I can make #box be replaced by #box?
One thing to keep in mind is that I cannot edit the HTML, so this needs to happen with jQuery only.

هل كانت مفيدة؟

المحلول

Just add > * after #box

$("#submit").click(function() {
    $("#box").load('/ajax/box/ #box > *');
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top