Home > database >  How to do a jQuery selection starting from a jQuery object
How to do a jQuery selection starting from a jQuery object

Time:06-14

In Vanilla JavaScript, one way to select an element from the DOM is:

let element = document.querySelector('[css selector]');

You can then use this element to select elements within this element, which can be done like this:

element.querySelector('[other css selector]');

I tried looking it up on jQuery's documentation, but couldn't find anything. Is there a way to do this in jQuery? Maybe something like:

let element = $('[css selector]');
element.select('[other css selector]');

// or maybe
$(element, '[other css selector]');

I know I can do this:

element[0].querySelector('[other css selector]');

But that is converting it back into a native element and then using the native JavaScript method. Is there a way to do this with only jQuery methods?

CodePudding user response:

In jQuery you can achieve identical behavior using jQuery.find(selector) method:

let $element = $('#some-div');
let $someGrandChildren = $element.find('b, i, u');

A less common approach is to use jQuery(selector[, context ]) method where the context argument could be a DOM Element, Document, jQuery or selector. So this works as expected too:

let $element = $('#some-div');
let $someGrandChildren = $('b, i, u', $element);

According to the documentation, this method uses .find() behind the scene.

CodePudding user response:

$('#thefirstselector .yoursecond .yourthird #fourth');
  • Related