Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery object understanding [duplicate]

I had to jump into jQuery development without getting too much time into learning all the associated basics, so there is one thing that throws me off quite a bit.

I see two different ways our developers access jQuery objects:

Case 1:

var container =  $("#containerId");

// Then use it as:
container.hide();

Case 2:

var container =  $("#containerId");

// Then use it as:
$(container).hide();

From my thin up to date knowledge, by wrapping a container as in var obj = $(container), we get a jQuery object obj that we can further work with.

But then why do I see intermittently developers wrapping it again when using as in $(obj).doSomething()?

Edit: the question suggested as duplicate is asking about best practices and although similar, my question is purely on understanding of jQuery object wrapping.

like image 324
eYe Avatar asked Feb 08 '16 15:02

eYe


2 Answers

Second wrapping does nothing as I remember. So if there can be a selector a dom element or a jQuery object you can just wrap it and do not care about what it was.

But if you know it is a jquery object, you shouldn't use wrapping.

like image 67
Qwertiy Avatar answered Nov 09 '22 22:11

Qwertiy


When developers develop a function, for example in a jQuery plugin, that can get a parameter that is either a DOM element or a jQuery object or a selector, then they use it:

function x(container) {
    container = $(container);
    // use container as a jquery object
}

// these both work:
x("#containerId");
x($("#containerId"));
x(document.getElementById("containerId"));
like image 33
Gavriel Avatar answered Nov 09 '22 21:11

Gavriel