Why does $('#id') return true if id doesn't exist?

前端 未结 6 706
野趣味
野趣味 2020-11-28 13:08

I always wondered why jQuery returns true if I\'m trying to find elements by id selector that doesnt exist in the DOM structure.

Like this:

6条回答
  •  一生所求
    2020-11-28 13:44

    You can come close to doing what you want by accessing the length the element, and combine with the ternary operator:

    console.log(!!$('#notfound').length);  // false
    console.log(!!$('#exists').length);    // true
    var element= $('#notfound').length ? $('#notfound') : $('#exists');
    console.log(element.attr('id'));  // outputs 'exists'
    

    As to the heart of the question:

    Wouldnt it be more logical if the ID selector returned null if not found?

    No, not for the JQuery way of doing things - namely, to support chaining of JQuery statements:

        $('#notfound').hide("slow", function(){
          jQuery(this)
            .addClass("done")
            .find("span")
              .addClass("done")
            .end()
            .show("slow", function(){
              jQuery(this).removeClass("done");
            });
        });
    

    Even though notfound doesn't exist this code will run without stopping script execution. If the initial selector returns null, you'll have to add in an if/then block to check for the null. If the addClass, find, end and show methods return null, you'll have to add an if/then block to check the return status of each. Chaining is an excellent way to handle program flow in a dynamically typed language like Javascript.

提交回复
热议问题