Alex Wohlbruck
Alex Wohlbruck

Reputation: 1436

Use jQuery method on object property

I am trying to use a jQuery function on a property of my js object, but it's giving me an error "Uncaught TypeError: Cannot read property 'jquery' of undefined". Here is some sample code:

var foo = {
    bar: $('#element'),
    baz: this.bar.find('#childelement'), // <- jQuery .find() not working
    hideBaz: function() {
        this.baz.hide();
    }
}

Not really sure what to do here, any help would be great

Upvotes: 0

Views: 33

Answers (3)

Vatsal
Vatsal

Reputation: 2128

To use jQuery you need to use namespace provided by jQuery. ie - either jQuery or $ which are given with jQuery. You can also create your own namespace by using jQuery.noConflict().

If you use them then only jQuery will know you are trying to access its methods with their objects. Something like $(this) or $("yourselector").

So with the above, you can use

var foo = {
    bar: $('#selector'),
    baz: $(this).bar.find('#childSelector'), 
    hideBaz: function() {
        this.baz.hide();
    }
 }

Hope this be of some help.

Happy Learning :)

Upvotes: 1

The Process
The Process

Reputation: 5953

you should wrap this in jquery :

var foo = {
    bar: $('#element'),
    baz: $(this).bar.find('#childelement'), 
    hideBaz: function() {
        this.baz.hide();
    }
}

Upvotes: 2

Kevin Wang
Kevin Wang

Reputation: 281

In order to enable jquery functionalities, you must use $(this) rather than just this. Without using $(this), you will not be able to use any jquery on that object.

Upvotes: 2

Related Questions