Search code examples
javascriptjqueryselectordocument-ready

What can cause jQuery selector to fail after document.ready when it works from console?


I use jQuery to select an (unique) ID from the DOM :

$(document).ready(
    alert("length :" +$("#btn").length)
);

The alert triggers when the page is still white (I don't know if it changes anything) and, nothing is selected (len is 0).

When I copy/paste the alert in the console, when the site is "visually" ready, the alert gives "length :1" as result.

for some reasons, either document.ready or the selector does not work.

I use jQuery 3.2.1.

The button itself is like that:

<ul class="nav navbar-nav">
    <li class="active"><a href="#">abc</a></li>
    <li><button class="btn btn-primary" type="button" id="btn">said button</button></li>
</ul>

Solution

  • We have to pass an anonymous function or named function (callback) inside a ready for it to work properly i.e. after the DOM load is completed.

    Try this:

    $(document).ready(function(){
                 //----^^^^^^^----------- here
       alert("length :" +$("#btn").length)
    });
    

    or the shorthand code (like every good developer out there uses)):

    $(function(){
       alert("length :" +$("#btn").length)
    });
    

    $(document).ready(function(){
           alert("length :" +$("#btn").length)
        
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul class="nav navbar-nav">
        <li class="active"><a href="#">abc</a></li>
        <li><button class="btn btn-primary" type="button" id="btn">said button</button></li>
    </ul>