Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload particular element with jQuery

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.

<script>
    $(document).ready(function() {
        $("#button").click(function() {
            $("#demo").load(location.href + "#demo");
        });
    });
</script>
</head>

<body>
    <div id="example">
        <p id="demo">hi</p>
        <button id="button" type="button">press</button>
    </div>
like image 686
Arun Kumaresh Avatar asked Apr 13 '16 06:04

Arun Kumaresh


People also ask

Can we reload a div?

Use ” #id > *” With . load() to Reload a div in JavaScript. Use window. setInterval() to Refresh a div in JavaScript.

How to refresh dom element in jQuery?

click(function() { location. reload(); }); The reload() function takes an optional parameter that can be set to true to force a reload from the server rather than the cache.

How do I refresh only part of a page in HTML?

Refreshing part of a page periodically You can use the frame “reload” function periodically in frameset page itself. In the above code, “right_frame” reloads every second. setInterval() function is very closely related to setTimeout() – both have similar syntax: setInterval ( expression, interval );


2 Answers

You 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.

like image 114
Tushar Avatar answered Oct 13 '22 21:10

Tushar


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())
  })
})
like image 41
Michał Perłakowski Avatar answered Oct 13 '22 21:10

Michał Perłakowski