Explanation of context in jQuery init Method
I always know that jQuery's initialization method is: $ (selector, context), but I recently read the code and found that context is not just as simple as limiting the search:
I have summarized the following points:
ABCDE
F
1. When selector is a String css selector, context is used to restrict the search domain. All elements to be searched are searched under the context.
Console. log ($ ("# n2"); // n2 console. log ($ ("# n2", $ ("# n3"); // [] console. log ($ ("span"); // All span consoles. log ($ ("span", $ ("# n2"); // n3
2. When selector is an html element, context can be a jQuery or Dom object. It can also be a property object of prop.
When context isJQuery and Dom objectsContext is used to provide the returned value.OwnerDocumentThe ownerDocument of the returned element is determined by the ownerDocument of context. The default value is document.
That is to say, if your context is under the current document, the ownerDocument of the returned element is also deleetn. If context is under an iframe, The ownerDocument of the returned element is also the document of iframe.
Console. log ($ ("") [0]. ownerDocument); // generate a span element. The context is the document console. log ($ ("", $ ("# n2") [0]. ownerDocument); // generate a span element. The context is the document console. log ($ ("", $ ("iframe" *02.16.content#doc ument) [0]. ownerDocument); // If iframe exists, a document whose context is iframe is generated.
When context isProp property objectThe context is used to provideGenerating element attributesOf:
console.log($("
", {Name:" 123 ", width: 455, class:" test "}) [0]. outerHTML) // Chrome:
3. When selector isJQuery or DomElement,Context is useless.. This is different from what I thought before. I thought it would filter again based on context, but after reading the source code, it was not.
In this case, context is completely ignored.
Console. log ($ ("# n2"); // n2 console. log ($ ("# n2"), $ ("# n3"); // n2, the console is not filtered. log ($ ("# n2") [0]); // n2 console. log ($ ("# n2") [0], $ ("# n3"); // n2, not filtered