2

I have a condition if my parent div has children with class .ads then it should alert('true') else alert('false'). But my function returns true in both cases. Here is jsFiddle link http://jsfiddle.net/F3EXf/

<head>
    <script type="text/javascript" src="jquery-1.7.2.js"></script>
    <script type="text/javascript">
        $(function(){
            if($('#me').find('.ads')){
                alert('true')
            } else {
                alert('false')
            }
        });
    </script>
</head>
<body>
    <div id="me">
        <div class="noads">aaaa</div>
    </div>
</body>

Hi vega Please see below screenshot

enter image description here

Jitender
  • 7,593
  • 30
  • 104
  • 210

5 Answers5

9

To check if an element exists use instead

if ($('#me').find('.ads').length) {
   ...
}

Since $('#me').find('.ads') will always return true (it returns a jQuery-wrapped empty object evaluated as a true value) even if the element targeted by find() doesn't exist

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • can you elaborate it more. why it is return true in all case – Jitender Sep 05 '12 at 12:51
  • because `.find()` method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. – Ahsan Khurshid Sep 05 '12 at 12:53
  • `find()` creates a jQuery wrapped node collection, evaluated as true in any case. What matters for your purpose is to check if that collection is empty or not – Fabrizio Calderan Sep 05 '12 at 12:54
  • @fabrizio: I want to learn more about jQuery wrapped node collection. Can your refer me any article or something related to jQuery wrapped node – Jitender Sep 06 '12 at 05:46
3

All jQuery selectors and traversing functions returns a jQuery object. jQuery object is an Array-Like object that has properties and reference to core functions.

A small example to show the list of properties and functions readily available in jQuery object http://jsfiddle.net/Tj9e8/1/

When you call the jQuery function as $(selector), It creates a jQuery object with wrapped list of matched element(s) based on the selector.

For example: When you do $('#test'), it creates a jQuery object and wraps DOM element with ID test.

Check the below code snippet from jQuery's .init function for handling for ID selector

elem = document.getElementById(match[2]); 
//match[2] is string 'test' in '#test' that was passed to $('#test')

if (elem && elem.parentNode) {
   if (elem.id !== match[2]) {
      return rootjQuery.find(selector);
   }
   //below 2 lines allows the jQuery object to behave like array like objects
   this.length = 1;
   this[0] = elem; //elem is nothing but the dom node.
}
this.context = document;
this.selector = selector;
return this; //Returns jQuery object

For more information check out the .init function code

Below is the snapshot of the $('#test').

enter image description here

As you can see the length is 0 but even still the $ function return jQuery object with length 0. This is to protect the next chained call instead of throwing an error.

In most cases, we select an element to run some function on it..

Ex: $('#test').addClass('example').

  1. Call's jQuery function using $('#test') with a string arguement '#test'
  2. jQuery call's .init above to determine the type of the argument and returns a jQuery object wrapped with matched elements(if any, else just jQuery object).
  3. Call .addClass on jQuery object, which internally iterate overs the list of matched elements and adds the class to the element. Below is snippet from .addClass function code

    if (value && typeof value === "string") {
        classNames = value.split(core_rspace);
        for (i = 0, l = this.length; i < l; i++) { 
        //^-- This is where it iterate over matched elements
            elem = this[i];
            if (elem.nodeType === 1) {
    

Now the points to note is,

  1. $ function always returns a jQuery object
  2. The jQuery object is nothing but a javascript object with the following

    a. Wrapped set of matched elements An example using .find

    b. properties - Sample that lists properties

    c. functions - Sample that lists functions

HTML:

<ul>
    <li>Test</li>
    <li class="red">Test</li>
    <li>Test</li>
    <li class="red">Test</li>
</ul>

JS:

var $lisample = $('ul').find('.red');

Not the wrapped set of matched elements as a result of .find looks like below,

enter image description here

More reading

  1. How do jQuery objects imitate arrays?
  2. jQuery object and DOM element
  3. http://blog.buymeasoda.com/does-calling-the-jquery-function-return-an-ob
Community
  • 1
  • 1
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
  • thanks for explaining it very clearly. you have posted screenshot with DOM. I want to check length of my selector so how to check this in DOM. Like you do – Jitender Sep 10 '12 at 05:50
  • I am searching .sub class in DOM, function work perfectly. but when i am looking in DOM it is showing its length 0. here is http://jsfiddle.net/rRNkb/. i am attaching DOM screenshot in my question – Jitender Sep 10 '12 at 06:46
  • @amit Did you see the snapshot.. the selector was `""`.. I am not able to replicate the issue that you mentioned.. and your fiddle works fine.. except for that missing `` tag. – Selvakumar Arumugam Sep 10 '12 at 13:23
  • Thanks for reply, i just want to know how to see length of selector in DOM – Jitender Sep 10 '12 at 13:55
  • @amit `$(selector).length` will return you the length of the selector(meaning matched elements count).. if that is what you want.. If not, please post and example and tell me what you expect and what was returned.. – Selvakumar Arumugam Sep 10 '12 at 14:02
  • I understand you answer, You post snapshot where you highlight length of "li.red" I want to know how to access to that tool. – Jitender Sep 10 '12 at 14:21
  • @amit It just a break point in the firebug. [setting break-point in firebug](https://getfirebug.com/doc/breakpoints/demo.html). After it stops at the breakpoint, check the Watch and inspect the selector variable. – Selvakumar Arumugam Sep 10 '12 at 14:26
  • Thanks a lot for you nice and valuable effort – Jitender Sep 10 '12 at 14:29
1
 $(function () {
        if ($('#me').find('.ads').length>0) {
            alert('true');
        } else {
            alert('false');
        }
    });
Thulasiram
  • 8,432
  • 8
  • 46
  • 54
1

I usually do this:

if(typeof variable != 'undefined')

so in your case:

if(typeof variable[0] != 'undefined'){

because .find function returns an array.

CODE

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $(function(){
                var variable = $('#me').find('.ads');
                if(typeof variable[0] != 'undefined'){
                    alert('true')
                } else {
                    alert('false')
                }
            });
        });
    </script>
</head>
<body>
    <div id="me">
        <div class="noads">aaaa</div>
    </div>
</body>
</html>

You can find info about typeof variable != 'undefined' here.

Community
  • 1
  • 1
tsergium
  • 1,176
  • 1
  • 14
  • 26
0

Fiddle link: http://jsfiddle.net/F3EXf/8/

1.If you need to look for an element's children, use Children() straight away. 2.Also, try counting the elements that are resulted from your selector and then decide if its available

$(function(){
    var children = $('#me').children('.noads');
if(children.length > 0){
    alert('true')
    }

    else {
        alert('false')

        }
})

for Demo, look for the fiddle link provided above.

To answer your question, why it alerts as true if the element is not present.

  1. It returns an empty array but not a null array... It means it has some information in the resulting object but length is 'zero' but actually it is not null or undefined
Dhanasekar Murugesan
  • 3,141
  • 1
  • 18
  • 21