Oops! It appears that you have disabled your Javascript. In order for you to see this page as it is meant to appear, we ask that you please re-enable your Javascript!

Why does jQuery or a DOM method could not find the element?

As script executed line by line, they are only executed when they are added into the DOM. The order matters. This mean the script cant find the element which written later below as it is not added into the DOM yet. Example:


<div id="fname">test</div>


The result for first document.getElementById is null. However, there is value for the second one.

What should you do?

There are few option to solve this.

        1. Move your script to where your action will be fire
              document.getElementById("fname").addEventListener("focusout", function() {
        2. Use $(document).ready()
          This will parse all the codes into the DOM first before executing them.

        3. Use Delegated Events .On()
          Delegated events can process events from descendant elements that are added to the document at a later time.

            $(document).on("click", {val: "test"}, display);
            function display( event ) {
            alert( "display: " + event.data.val );
          click me

Either way can solve the problem.

Is best to use the $(document).ready(), this will ensure all events will be registered in DOM before executing them.

$(document).ready(function() {
   // do stuff when DOM is ready


$(function() {
    // do stuff when DOM is ready

For more information of this, refer here.


Leave a Reply

Your email address will not be published. Required fields are marked *