How to extend jQuery replaceWith function to accept callback function?

It should be easy, right? However, I cannot sem find any examples of such functionality anywhere. The problem is that after doing replaceWith (), I want to do something with the elements that were written to the DOM, but if I try to do something with them right after the replaceWith () call, they don't exist yet. I have to be sure that replaceWith () is completely finished. I just want something like this to work:

$('#foo').replaceWith('some text', function() { //do something else here }); 

Thoughts?

+4
source share
2 answers

You can create your own function that calls replaceWith :

 $.fn.replaceWithCallback = function(replace, callback){ var ret = $.fn.replaceWith.call(this, replace); // Call replaceWith if(typeof callback === 'function'){ callback.call(ret); // Call your callback } return ret; // For chaining }; 
+4
source

Create a callback function simply:

 $("#myElement").replaceWith(function() { // call a function ); 

and replace the word, not the internal html:

 $("#derp").text(function(index, text) { // call a function here return text.replace('old', 'new'); }); 
0
source

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


All Articles