jQuery custom filter problem: element stack is way too much
I am trying to implement ":random" selector which selects a random element from a stack of elements.
Here's the code: http://jsfiddle.net/nuSWF/
The problem is the开发者_开发技巧 selector sometimes tries to select an element which does not exist(out of index). So I prepared the demo code which highlights the cause but I don't understand why. I seems it is a bug or something.
P.S: I know I could select a random element with other methods but this time I have to implement this, also wondering what's going on inside.
What you're seeing with the stack length is normal, it's just evaluating the :random
selector on all <a>
elements in mydiv1
before the >
child selector, so the length at that point is 4.
For example, this would produce the result you're expecting:
var elements2 = $('#mydiv1>a').filter(':random');
You can test it out here.
So what's happening overall is your selector is indeed filtering to random <a>
elements...but those may or may not be further filtered out by the >
child selector later (if they're under a <span>
, they get filtered). This is true of all selectors if you think about it...any filter you perform just reduces the set of elements...they may further filtered later by more selectors.
精彩评论