Skip to main content

jquery $(selector).ready() code running even if no element was matched



I am using this code to only run this js on certain pages.







$("body#action_new").ready(function() {

console.log($("body#action_new"));

console.log($("body#action_new").length);

console.log("code is running");

}







Even though body#action_new does not exist, the code is running.





the two console.logs print out:







[]

0

code is running







What gives?


Comments

  1. you cannot call the ready except on the document, intead you can try

    $(document).ready(function(){

    if($("#action_new").size()>0){
    console.log($("body#action_new"));
    console.log($("body#action_new").length);
    console.log("code is running");
    }

    });


    as stated by @Interrobang in the comments the .size() method internally uses .length so it is advised to use .length to avoid the additional overhead of a function call, so the above code would look like

    if($("#action_new").length )>0){

    ReplyDelete
  2. You cannot call .ready() on anything but document. You will get undefined behavior in any other case.


    The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.


    http://api.jquery.com/ready/

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?