I have an array of values of the form:
configs = ["26W", "27W", "28W"...]
They correspond to some of the a elements in a list:
<ul id="value-list"><li><a data-value="26W">...</a></li>
<li><a data-value="27W">...</a></li>...</ul>
When the data in the list does correspond to an existing a, I need to set the parent li class to "available" and not "unavailable". If there is an a with a value not in the list, I need to set the class to "unavailable" and not "available". (Edit: I realize that having both classnames is redundant, but I don't have the option to change that right now.)
I can think of two ways to do this:
Iterate
var $allSwatchItems = $("#value-list > li");
$allSwatchItems.each(function () {
var $this = $(this);
var $a = $this.children("a");
if (configs.indexOf($a.attr("data-value")) === -1) {
$this.addClass("unavailable").removeClass("available");
} else {
$this.addClass("available").removeClass("unavailable");
}
});
Two-step
var $allSwatchItems = $("#value-list > li");
// Set everything to unavailable at first.
$allSwatchItems.removeClass("available").addClass("unavailable");
// Build the selector for the swatch anchors.
var swatchSelector = configs.map(function (val, idx, arr) {
return "a[data-value='" + val + "']";
}).join(", ");
// Set the matching list items to available.
var $availSwatchItems = $allSwatchItems.children(swatchSelector).parent();
$availSwatchItems.removeClass("unavailable").addClass("available");
I know there are pros and cons to both approaches, but is one significantly better than the other (and how), or is there a third approach I should consider?
Update: Here's how I finally did it:
function checkAvailable() {
if (-1 !== $.inArray($(this).children("a").attr("data-value"), configs)) {
return "available";
} else {
return "unavailable";
};
}
$("ul#value-list > li").removeClass("unavailable available").addClass(checkAvailable);
configs? Do you mind about cross browser compatiblity? \$\endgroup\$configsis the name of the array I mentioned at the very beginning. I have polyfilledArray.prototype.mapfor old browsers. What other cross-browser issues are there? \$\endgroup\$indexOfworks on arrays starting IE9 only :) developer.mozilla.org/en-US/docs/JavaScript/Reference/… \$\endgroup\$