I want to re-use jQuery selections to be able to do further sub-selections. This is my example:
if ($('#thisId > .thatClass').length > 0) {
return $('#thisId > .thatClass > a.thatOtherClass').attr('id');
}
As I make extensive use of selections, I want (at least for readability reasons) to shorten the code to look similar to this:
var selection = $('#thisId > .thatClass');
if (selection.length > 0) {
var furtherSelection = selection.filter('> a.thatOtherClass');
return furtherSelection.attr('id');
}
Trying this I get an error:
TypeError: furtherSelection.attr(…) is undefined
Clearly I’ve got something wrong, maybe someone has an idea?
Us
children()instead…I’ve used
children()due to the fact that the use of>in selectors is to be deprecated (as per comments below).If you weren’t looking specifically for child elements then you could use
find()like this…