I'm trying to reload particular element on button on click using jQuery, but when I click the button, the entire page gets loaded in this element. I have tried the following code which loads the entire page in this element. I want to load only particular element.
$(document).ready(function() {
$("#button").click(function() {
$("#demo").load(location.href + "#demo");
});
});
<div id="example">
<p id="demo">hi</p>
<button id="button" type="button">press</button>
</div>
I'm trying to reload particular element on button on click using jQuery, but when I click the button, the entire page gets loaded in this element. I have tried the following code which loads the entire page in this element. I want to load only particular element.
$(document).ready(function() {
$("#button").click(function() {
$("#demo").load(location.href + "#demo");
});
});
<div id="example">
<p id="demo">hi</p>
<button id="button" type="button">press</button>
</div>
Share
Improve this question
edited Oct 7, 2022 at 17:37
KyleMit♦
29.9k72 gold badges506 silver badges697 bronze badges
asked Apr 13, 2016 at 6:53
Arun KumareshArun Kumaresh
6,3116 gold badges35 silver badges50 bronze badges
3 Answers
Reset to default 18You can use load()
with selector.
$("#demo").load(location.href + " #demo"); // Add space between URL and selector.
^
This will load only the #demo
element from the location.href
URL.
You have to load the page using $.get()
and extract the #demo
fragment:
$("#button").click(function() {
$.get(location.href).then(function(page) {
$("#demo").html($(page).find("#demo").html())
})
})
You can use Ajax, then create element with responseText, then put it into the div:
<head>
<script>
$(document).ready(function() {
$("#button").click(function(){
$.ajax({
url: location.href,
type: 'GET',
sucess: function(data)
{
refreshedPage = $(data);
newDemo = refreshedPage.find("#demo").html();
$('#demo').html(newDemo)
}
});
}
}
</script>
</head>
<body>
<div id="example">
<p id="demo">hi</p>
<button id="button" type="button">press</button>
</div>
</body>
But You load the entire page, it might me not usefull. I suggest to make a php script which just returns the requested data, and call it via Ajax at page load and at button click...