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.
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.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With