How can I use load () to update a div without duplicating an element?

I use this code to update a div with id="my" :

 <script type="text/javascript"> function recp() { setInterval(function() { $("#my").load(location.href+ ' #my'); }); } </script> <div id="my"><?php echo date('a:i:s'); ?></div> 

It works, but it generates this code:

 <div id="my"><div id="my">pm:25:40</div></div> 

How to update a div without creating a double div?

In other words, how to update only this div:

 <div id="my"><?php echo date('a:i:s'); ?></div> 
+4
source share
3 answers

add another div as a container and load it into it.

 <script type="text/javascript"> function recp() { setInterval(function() { $("#result").load(location.href+ ' #my'); }); } </script> <div id="result"> <div id="my"><?php echo date('a:i:s'); ?></div> </div> 
+6
source

Modify your code to use $.get() instead of .load()

 <script type="text/javascript"> function recp() { setInterval(function() { $.get(location.href, function(data){ $('#my').empty().append( $(data).find('#my').children() ); }); }); } </script> 
+1
source

You can try:

 <script type="text/javascript"> function recp() { setInterval(function() { $("<div/>").load(location.href+ ' #my', function(response, status, xhr) { $("#my").replaceWith(response); $(this).remove(); }); }); } </script> 
0
source

Source: https://habr.com/ru/post/1386424/


All Articles