How do you replace an element in jQuery and have the replacement element returned instead of the element that was removed?
I have the following scenario. I have many checkboxes and once you click one of them, that checkbox is replaced by a loading icon. Once some AJAX stuff happens, the loading icon is replaced by a tick icon.
Using jQuery's replaceWith
, you'd do something like:
$("input[type='checkbox']").click(function() { $(this).replaceWith("<img src='loading.jpg' alt='loading'/>"); $.post("somepage.php"); $(this).replaceWith("<img src='tick.jpg' alt='done'/>"); });
However, this doesn't work because replaceWith
returns the element that was removed, not the one which was added. So after the AJAX stuff completes, loading.jpg
will just stay there forever.
Is there some way I can return the replacement element without selecting it?
Thanks in advance.
To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.
The replaceWith() method in jQuery is used to replace the selected elements with the new one. This method replaces the matched elements with the specified HTML elements. It returns the replaced elements. This method is similar to the replaceAll() method.
Answer: Use the jQuery . appendTo() Method You can use the jQuery . appendTo() method to move an element into another element.
Give the loading image a class, then in the post callback, use the class as a selector to find the image you've just injected.
$("input[type='checkbox']").click(function() { $(this).replaceWith("<img src='loading.jpg' alt='loading' class='loading-image' />"); $.post("somepage.php", function() { $('.loading-image').replaceWith("<img src='tick.jpg' alt='done'/>"); }); });
If you may have several of these running at a time, you can get the closest parent of this
and use that as the context when searching for the class.
EDIT: Another alternative that uses a variable to store the new element and removes the need to apply the class and search for the new element when the function returns.
$("input[type='checkbox']").click(function() { var loading = $("<img src='loading.jpg' alt='loading' />"); $(this).replaceWith(loading); $.post("somepage.php", function() { loading.replaceWith("<img src='tick.jpg' alt='done'/>"); }); });
Create an element and use it as parameter to replaceWith:
$('input[type=checkbox]').click(function() { var img = document.createElement('img'); img.src = 'loading.jpg'; $(this).replaceWith(img); $.post('somepage.php', function() { $(img).replaceWith('<img src="tick.jpg" alt="done"/>'); }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With