CSS selector for grouped iterations
I have a range of items that I want to iterate over as groups. Consider this HTML:
<input class="matching match-1" />
<input class="matching match-1" />
<input class="matching match-2" />
<input class="matching match-2" />
<input class="matching match-2" />
<input class="matching match-3" />
<input class="matching match-3" />
// etc
I want a CSS selector that would allow me to iterate over them as groups so that there are - using this example - 3 loop iterations (one for match-1, one for match-2 and one for match-3). 1,2,3, etc. is the variable used for grouping, but this is not fixed so it cannot rely on hardcoding those values. Is it possible? I'll be using jQuery or a prototype, but that shouldn't matter.
thanks
a source to share
Try the following:
var groups = [];
$(".matching").each(function(index, elem) {
if (this.className.match(/(?:^|\s+)match-(\d+)(?:\s|$)/)) {
if (typeof groups[RegExp.$1] == "undefined") {
groups[RegExp.$1] = [];
}
groups[RegExp.$1].push(this);
}
});
This will iterate over the list of items with a matching class, checks if it also has a class of form-x, gets x, and adds it to the list of matching groups using x as the index.
a source to share
There is nothing like the description in standard CSS2 (that is, an implementation that is currently widely supported).
CSS3, however, has more flexible selectors, and luckily for you, they are all implemented in jQuery.
Try something like this:
$("input[name^='match-']")
This will return a jQuery collection of DOM nodes that matches what you are trying to do. You can iterate with classic JS or jQuery .each()
.
a source to share
input[class^="matching match-"]
must work. I'm not sure what you mean by grouping.
Edit:
var groups = [];
var classes = {};
$('input[class^="matching match-"]').each(function() {
classes[$(this).attr('class')] = 1;
});
for (c in classes) {
groups.push($('input[class="'+c+'"]'))
}
a source to share