Atomic Habits

[jQuery] $( "span", this ) Selector 본문

IT/JavaScript-JQuery

[jQuery] $( "span", this ) Selector

체계성 2022. 7. 4. 10:32

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" ).

 

https://api.jquery.com/jquery/#jQuery-selector-context

Comments