in jQuery function:
.on(event, [selector,] [data,] handler)
How jQuery parse this call:
on('click', 'tag3', () => {})
tag3 is selector or data?
in jQuery function:
.on(event, [selector,] [data,] handler)
How jQuery parse this call:
on('click', 'tag3', () => {})
tag3 is selector or data?
The last argument must be the handler. So if there are two arguments there there is no data and no selector.
If there are four arguments than the second one must be selector and the third one must be data.
So it only becomes tricky if there are exactly three arguments.
If the second argument isn't a string, then it can't be a selector, so it must be data.
If it is a string then it could be a selector or data. Now jQuery could do some heuristics by running it through the selector engine and seeing if it is a valid selector … but it doesn't. It just assumes that if the second argument is a string then it is a selector.
How jQuery distinguish between 'data' and 'selector' parameter?
They have a different data-types
data - is a plain object (not a DOM or jquery object)
selector - is a string or a jquery/DOM/DOM-array object.
so, jquery can make out whether an argument is a selector or data by judging the properties of the argument, for example this and this
return obj instanceof HTMLElement; //to check if it is a DOM object
or
return obj instanceof jQuery; //to check if it is a jquery object
tag3 is selector or data?
As per documentation
If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with ). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements.
If the string passed to jquery method is an HTML then subsequent object is either a document (DOM object) or an attributes object.