Note that there are some explanatory texts on larger screens.

plurals
  1. POReturn "True" on Empty jQuery Selector Array?
    primarykey
    data
    text
    <p>I'm working on creating a more semantic way of checking for elements with jQuery. Using <code>$("#element").length &gt; 0</code> just doesn't really feel very well worded to me, so I'm making my own selector addition for use in <code>.is</code>:</p> <pre><code>if($("#element").is(":present")) { console.log("It's aliiiveeee!!"); } </code></pre> <p>That part was easy, like this:</p> <pre><code>$.extend($.expr[':'],{ present: function(a) { return $(a).length &gt; 0; } }); </code></pre> <p>I want to go a step further, and make it easy to see if an element doesn't exist, using similar syntax:</p> <pre><code>$.extend($.expr[':'],{ present: function(a) { return $(a).length &gt; 0; }, absent: function(a) { return $(a).length === 0; } }); $(function() { if($("#element").is(":absent")) { console.log("He's dead, Jim."); } }); </code></pre> <p>But this part is surprisingly hard to do. I think it's because I'm paring down the returned elements to get a result, and paring the selector to .length === 0 is the same as asking for no elelements: it returns false no matter what.</p> <p>I've tried a lot of different ways to reverse things and get this to return true when the element doesn't exist, and false if it does:</p> <pre><code>return $(a).length === 0; return !($(a).length &gt; 0); if(!($(a).length &gt; 0)) { return true; } if($(a).length &gt; 0) { return false; } else { return true; } return !!($(a).length === 0); // etc... </code></pre> <p><strong>Is there an easy way to get this to just return true if the element doesn't exist, and false if it does?</strong></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload