Very simple JSFiddle demonstrates the problem (you’ll need to view a debug console since console.log is used to demonstrate the problem). The 2nd console.log statement is empty. However the code works if I removeel from the following line:
var items = $('li[data-level="2"]', el);
so that it becomes:
var items = $('li[data-level="2"]');
then the code works. Can anyone explain why this is? Don’t know why the line declaring el would be missing, it’s showing for me in JSFiddle, but here’s all the code in the JavaScript panel:
$(document).ready(function() {
var el = $('ul');
var items = $('li[data-level="2"]', el);
console.log(items);
var visible = items.filter(':visible');
console.log(visible);
});
You have all of the
lielements set todisplay:none, which is whyel.filter(':visible')returns an empty collection. I’m not sure I see the problem here.jQuery’s
$.filtermethod will return all of the items in the collection that match the selector passed into the filter. So if we were to select all list items, and strong items:And then filter it so that we only have list items:
Our result would only be list items. In your case, you have created an unordered list, replete with three hidden list items. You have selected all of these, and then attempted to filter them to only see those that are
:visible, but since you hid them all withdisplay:nonein your CSS, the resulting collection will be empty.jQuery is worked as expected.