How to apply additional selectors after storing selected objects

I want to reuse jQuery variations in order to be able to do additional subsamples. This is my example:

if ($('#thisId > .thatClass').length > 0) { return $('#thisId > .thatClass > a.thatOtherClass').attr('id'); } 

Since I use highlighting extensively, I want to (at least for readability) shorten the code so that it looks something like 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 message:

TypeError: furtherSelection.attr (...) - undefined

It’s clear that something is wrong with me, maybe someone has an idea?

+4
source share
2 answers

Us children() instead ...

 var selection = $('#thisId > .thatClass'); if (selection.length > 0) { return selection.children('a.thatOtherClass').attr('id'); } 

I used children() because using > in selectors should be deprecated (as indicated below).

Unless you specifically looked for children, you can use find() like this ...

 var selection = $('#thisId > .thatClass'); if (selection.length > 0) { return selection.find('a.thatOtherClass').attr('id'); } 
+6
source

Instead, you can use .children() , as Archer suggests, and you should . But the main problem is that you use .filter when you mean .find . Archer hints at this, but it’s important to understand that there was no problem with your design ("> a.thatOtherClass") , except for best practice.

filter does not cross the DOM tree; it removes elements from the current sequence at the same DOM level. So, when you wrote this:

 var furtherSelection = selection.filter('> a.thatOtherClass'); 

You really said "elements that satisfy '#thisId > .thatClass' AND ALSO '> a.thatOtherClass' ." So you tested your average .thatClass elements when you were supposed to test your children. If you used find or children , this would work:

 var furtherSelection = selection.find('> a.thatOtherClass'); //works var furtherSelection = selection.children('a.thatOtherClass'); //also works 

See them in action on jsFiddle: http://jsfiddle.net/jmorgan123/S726f/

I point this out because the difference between .filter and .find very important, and your real problem was that you are confusing the two.

+1
source

All Articles