0

I don't have an issue, but have had times when I got code that didn't work because there was a jQuery object inside another jQuery object.

So I'm just looking for some clarity on the matter. I've looked for answers on this but haven't found anything.

Can we have:

var element1 = $("some-element");
$(element1).addClass("hidden");

Not sure if I'm just stupid (by no means a JavaScript or jQuery expert. I'm still quite junior), but I just wanted to find out what the deal with this is.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Deshen
  • 73
  • 8
  • 3
    [`jQuery()`](http://api.jquery.com/jquery/#cloning-jquery-objects): _"When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one."_ – Andreas May 26 '17 at 14:00
  • Can you please create fiddle and explain in detail? – Jay May 26 '17 at 14:13
  • Thanks for the comments. A fiddle to explain a bit more. [fiddle](https://jsfiddle.net/hkzp32r8/15/) – Deshen May 26 '17 at 14:24

3 Answers3

0

you don't need to use like this you can just use this way

var element1 = $("some-element");
element1.addClass("hidden");

you can you jquery object inside jquery object.

Jay
  • 703
  • 9
  • 21
0

I can for example this, hope to have the same idea with your problem

function buildArray(variable){
    if (variable.constructor === Array) return variable;
    return toArray(variable);
}

So, when i call buildArray function and pass variable parameter, it was Array. I can call member function of Array from buildArray.

Example:

var arr = [1, 2, 3, 4];
var index = buildArray(arr).indexOf(4);

With your question, can jQuery check with $() function.

Canh Nguyen
  • 333
  • 1
  • 18
0

I am still confused by the question, even with the fiddle..

Correct me if I am wrong, but assigning the name $element1 to a variable would behave no differently than using the name element1. It is simply used as a naming convention (Hungarian Notation) in order to:

distinguish jQuery objects which are stored in variables from other variables

But using $("#element1") is effectively selecting HTML element(s) for manipulation.

I have modified your Fiddle example, this would be my approach personally (although to be honest, this question is almost a little too broad and open to interpretation).

Sandman
  • 2,247
  • 1
  • 13
  • 26
  • All I really wanted to find out is why my example doesn't work. – Deshen May 29 '17 at 12:29
  • Thanks for the answer, It does not explain my question. I want to know why putting a jQuery object inside another jQuery object does not work. `$variable-name` vs `variable-name` has nothing to do with my question. If you take a closer look at the fiddle I linked in an earlier comment it should make more sense. – Deshen Jun 02 '17 at 06:47