When I execute the following code, it behaves like I expect (logs the contents of the DIV
element):
var html = '<form action="/" method="get" name="myform"><div>123</div></form>';
console.log($('div', html));
What I can't understand is why the following code does NOT work:
var html = '<form action="/" method="get" name="myform"><div>123</div></form>';
console.log($('form', html));
They seem the same, so why does the DIV
selector work when the FORM
selector does not?
Quite simply, the second example doesn't work because there is no element to find within the context of the string, whereas in the first example, there is a div that exists within the context of the string.
In jQuery, the format $('div', html)
means find the div element within the context of the html
variable. It's equivalent to $(html).find('div')
. See http://api.jquery.com/jQuery/#expressioncontext
Selector Context By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, to do a search within an event handler, the search can be restricted like so:
$( "div.foo" ).click(function() { $( "span", this ).addClass( "bar" ); });
When the search for the span selector is restricted to the context of this, only spans within the clicked element will get the additional class.
Internally, selector context is implemented with the .find() method, so
$( "span", this )
is equivalent to$( this ).find( "span" )
.
Since your second example has no form within the string's content (only a div is within it), it finds no match.
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