Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form selector not work working on dynamic markup

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?

like image 586
Pavel Eremin Avatar asked Oct 31 '22 17:10

Pavel Eremin


1 Answers

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.

like image 56
j08691 Avatar answered Nov 12 '22 13:11

j08691