patternjavascriptMinor
Setting TabIndex efficiently
Viewed 0 times
tabindexsettingefficiently
Problem
Is there a more efficient way to write this? Seems redundant to me:
var leaves = $(".leaf");
var trees = $(".tree");
$(".my-class").on("click", function (e) {
if ($(e.target).hasClass("leaf")) {
trees.each(function() {
$(this).attr("tabIndex", -1);
});
leaves.each(function() {
$(this).attr("tabIndex", 1);
});
} else {
trees.each(function() {
$(this).attr("tabIndex", 1);
});
leaves.each(function() {
$(this).attr("tabIndex", -1);
});
}
});Solution
.attr() can work on all jQuery matched elements at once.Assuming that performance isn't a concern, I think that the clearest way would be to "reset" all nodes to have a
tabIndex of -1 first.var leaves = $(".leaf");
var trees = $(".tree");
$(".my-class").on("click", function(e) {
leaves.add(trees).attr("tabIndex", -1);
var selected = $(e.target).hasClass("leaf") ? leaves : trees;
selected.attr("tabIndex", 1);
});Code Snippets
var leaves = $(".leaf");
var trees = $(".tree");
$(".my-class").on("click", function(e) {
leaves.add(trees).attr("tabIndex", -1);
var selected = $(e.target).hasClass("leaf") ? leaves : trees;
selected.attr("tabIndex", 1);
});Context
StackExchange Code Review Q#45068, answer score: 3
Revisions (0)
No revisions yet.