Jitender
Jitender

Reputation: 7971

.find and .contents not working

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

Upvotes: 2

Views: 1290

Answers (5)

Dhanasekar Murugesan
Dhanasekar Murugesan

Reputation: 3229

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

Upvotes: 0

tsergium
tsergium

Reputation: 1176

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.

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

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

Upvotes: 3

Thulasiram
Thulasiram

Reputation: 8552

 $(function () {
        if ($('#me').find('.ads').length>0) {
            alert('true');
        } else {
            alert('false');
        }
    });

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

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

Upvotes: 9

Related Questions