简体   繁体   中英

how to limit the jquery search scope

It looks like JQuery does the search in the current document when using a selector.

How to search for an element only inside a div element?

jQuery selectors work very much like CSS selectors, which you may be more familiar with.

First, select the div, and then descend from that:

$('#my-div').find('some-selector').

or build your selector to match children of the element in question:

$('#my-div some-selector')

Old question, but everyone seems to have missed the scoped jQuery selector (using the scope you desired, ie your div selector, as the second parameter)

eg use

var $matches = $('.adiv', '#mydiv');

This is a shorter equivalent of:

var $matches = $('#mydiv').find('.adiv');
var elems = jQuery(".foo", jQuery("#divYourWantToLimitTo") );  //BAD
//or
var elems = jQuery("#divYourWantToLimitTo .foo");  //Better
//or
var elems = jQuery("#divYourWantToLimitTo").find(".foo");  //BEST

jQuery provides several ways to search for specific elements:

$("#your_div").find(".your_things");        //Find everything inside
  //-or-
$("#your_div").filter(".your_things");      //Find only the top level
  //-or-
$("#your_div .your_things");                //Easiest
var elements = $('div ' + yourSearch);
$('div-selector').find('the selector-you-are-looking-for');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM