How can I call a function after an element has been created in jquery?

Creating an element does not mean much, unless it is inserted into the page. I think that is what you mean by ready function.

The onLoad event is limited to certain elements only, and is not supported for div or p elements. You have to options:

You can use setInterval function to check the existence of the element. Once the element is found, you can clear the interval:

var CONTROL_INTERVAL = setInterval(function(){
    // Check if element exist
    if($('#some-element').length > 0){
        // Since element is created, no need to check anymore
        clearInterval(CONTROL_INTERVAL);
    }
}, 100); // check for every 100ms

The second and the more idiomatic way is adding a mutation observer on the target element, and checking if the element is one of the elements inserted elements whenever target is mutated, i.e new element is added:

let el = document.createElement("div");
el.innerHTML = "New Div";

const targetNode = document.querySelector("body");

const observerOptions = {
  childList: true,
  attributes: true,
  subtree: false
};

function callback(mutationList, observer) {
  mutationList.forEach((mutation) => {
    mutation.addedNodes.forEach((node) => {
      const isAdded = node.isEqualNode(el);
      console.log(isAdded);
    });
  });
}

const observer = new MutationObserver(callback);
observer.observe(targetNode, observerOptions);

document.body.appendChild(el);

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

There are two more alternatives, adding event listener for DOMNodeInserted or DOMNodeInsertedIntoDocument events but since MutationEvent is deprecated, it is best to avoid them.

https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent


You may want to look into jQuery live events. You attach an event handler to a selector that either matches now or after additional elements are created in your DOM.

So if you have a <ul> and you dynamically create new <li> items, in your $(document).ready() you can wire up a selector to an event handler so that all of your <li> elements will be wired for that event.

Here's a jsFiddle sample that demos live.

Hope this helps.


How are you creating the element?

If you're creating it in the static HTML then just use .ready(handler) or .on("load", handler). If you're using AJAX though that's another kettle of fish.

If you're using jQuery's load() function then there's a callback you can run when the contents been loaded:

$('#element').load('sompage.html', function(){ /* callback */ });

If you're using jQuery's $.ajax or $.get/$.post functions then there's a success callback in that:

$.ajax({
  url: 'somepage.html',
  success: function(){
    //callback
  }
});

If you're just creating the element and appending it like this:

$('body').append('<div></div>');

Then you can do this instead:

$('<div />', { id: 'mydiv' }).appendTo('body').ready(function(){ /* callback */ });

But this won't matter - because it's synchronous (which means that the next line of code won't run until it's added the element to the DOM anyway... - unless you're loading images and such) so you can just do:

$('<div />', { id: 'mydiv' }).appendTo('body');
$('#mydiv').css({backgroundColor:'red'});

But acctually, saying THAT you could just do this:

$('<div />', {id:'mydiv'}).appendTo('body').css({backgroundColor:'red'});