Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find $.find('selector') versus $('selector') difference

I've got a question why these two code snippets are different.

$('#ctl00_DDMenu1_HyperLink1')  
//jQuery(a#ctl00_DDMenu1_HyperLink1 Default.aspx) Console output
$('#ctl00_DDMenu1_HyperLink1').text()

The code above returns : Some link text

But

$.find('#ctl00_DDMenu1_HyperLink1')  
//[a#ctl00_DDMenu1_HyperLink1 Default.aspx] Consolee output
$.find('#ctl00_DDMenu1_HyperLink1').text()

Returns

TypeError: $.find("#ctl00_DDMenu1_HyperLink1").text is not a function

Does this mean that $.find return Array object [] and jQuery functions are not accessible?

//EDIT

I've used jQuery 1.4.2 & used Firebug Console.

//Answer found by practise

This code will return jQuery object reference and all jQuery function are accessible.

$('any_selector')
//jQuery(item1),jQuery(item2),...,jQuery(item-N) Console output $('any_selector').text()

This code return JavaScript Array object so any function of jQuery cannot be applied to resultset. Even when resultset seems to be identical.

$.find('any_selector')
//[item1,item2,...,item-N] Consolee output
$.find('any_selector').text()

But we can do trick (weird trick) to wrapp js Array into jQuery selector:

$($.find('any_selector_as_inner_select')).val()

//Thanks for help guys!

like image 838
r.piesnikowski Avatar asked May 21 '11 16:05

r.piesnikowski


1 Answers

The reason this does not work is because find() lets you filter on a set of elements based on a selection you've already made.For example if you wanted to select all of the inputs within a particular form, you could write:

$('#aParticularForm').find('input') 

It cannot be called on its own.

like image 50
cm2 Avatar answered Oct 22 '22 00:10

cm2