Thread:Manual talk:Coding conventions/JavaScript/jQuery objects vs. DOM objects/reply

ID selectors are incapable of returning more than one element. So if you're referring specifically to code using  on an object from an ID selector, that doesn't deserve mention in code conventions as it is imho just plain stupid. Something you might be confused by once, but if we start including things like that there is no telling where it will end end. Code conventions isn't a training guide to how the browser works and how the DOM works.

For passing around 1 element, you can use  instead of   to yield a cloned jQuery object that only contains the first node of the jQuery object collection.

Regarding passing HTMLElement objects or jQuery collections between functions, it depends on what makes sense for the situation. I don't think this is the kind of thing where there is 1 right solution or where using different approaches in different modules makes code harder to use.

jQuery plugins obviously operate on a jQuery collection as they are methods on the jQuery prototype itself. Utilities often operate on 1 single element. In the latter case it is imho preferred to document the method as taking an HTMLElement as opposed to a "jQuery object that must have only 1 element". That way the responsibility of extracting the right data is in the hands of the caller. So that you have  instead of. That way  doesn't have to verify it has length, take the first one, and maybe throw an error if it has more than one?

Also note that constructing a jQuery object for a node is very cheap. It is the first executive use case in the constructor. Nothing to worry about there. Things like  in DOM callbacks are very common and very fast.

So something like this would be fine:

However if utilities are more efficient when they can cache data outside a loop, then you may want to change the function to take an array-like object instead of requiring the callee to make a loop where  then has to do initialisation for every single call inside the loop.

So, instead of this:

The following would likely be better (so that  is only normalised once):

This sort of a bad example since jQuery methods support setting on the entire collection at once, so this is probably better done like  but you get the idea. Also, you could extend  with   so that it supports both: