Matching combined results in jQuery – ordered correctly

Today I used the “selector1, selector2, selectorN” selector in jQuery and was confused that, in some cases, when looping over the results I got them in the order of the selectors and not in the order of the elements in the page. I had expected it to work as an OR operator. My code looked like this:

var headers = $('h1,h2,h3', context);
headers.each(function(index) { ... });

First my function was called for all h1s, then for all h2s, etc, regardless of their ordering in the page. Some googling finally led me to this solution: first find all headers and then filter out the ones I need. My first try looked like this:

var headers = $(':header', context).filter('h1,h2,h3');
headers.each(function(index) { ... });

It didn’t work, unfortunately. There was no difference. After some reading I finally produced this less elegant but working solution:

var headers = $(':header', context).filter(function() {
	return $(this).is('h1,h2,h3');
});
headers.each(function(index) { ... });

This gave the desired result. The “:headers” selector was very useful for me this particular time, obviously. It needs to be replaced for the particular set of elements one is looking for of course, and if worst comes to worst, maybe ‘*’ is the only solution, even though it probably will have a bad effect on performance.