Reputation: 45
My coding is working fine, just wondered if there is more tidy way to write jQuery code? I was searching for this internet but cant find examples.
There are three duplicated class name with different selectors having different CSS settings. I would like to know if there is clean coding for this.
if ($(this).hasClass('toggle')) {
$(".toggle > span:first").css({
// something...
});
$(".toggle > span:nth-child(2)").css({
// something...
});
$(".toggle > span:last").css({
// something...
});
}
Is there similar to SCSS way? Like below
.toggle {
span {
&:first-child { // something... }
&:nth-child(2) { // something... }
&:last-child { // something... }
}
}
Thank you for taking time to look into this.
Upvotes: 0
Views: 60
Reputation:
if ($(this).hasClass('toggle')) {
$('.toggle > span')
.first().css({
// something...
})
.end().eq(2).css({
// something...
})
end().last().css({
// something...
});
}
Upvotes: 1
Reputation: 8346
You can use .end()
$(".toggle")
.children("span:first").css({"color":"blue"})
.end()
.children("span:nth-child(2)").css({"color": "green"})
.end()
.children("span:last").css({"color": "red"});
Or, use .filter()
$(".toggle")
.children("span")
.filter(":first").css({"color":"blue"})
.end()
.filter(":nth-child(2)").css({"color": "green"})
.end()
.filter(":last").css({"color": "red"});
Upvotes: 2
Reputation: 617
No, it`s not similar.
if ($(this).hasClass('toggle')) {
$(".toggle > span:first").css({
// something...
});
$(".toggle > span:nth-child(2)").css({
// something...
});
$(".toggle > span:last").css({
// something...
});
}
is similar to:
.toggle {
> span {
&:first-child { // something... }
&:nth-child(2) { // something... }
&:last-child { // something... }
}
}
Upvotes: 0
Reputation: 12391
You can iterate through on them:
var i = 0;
$(".toggle span").each(function($obj) {
console.log('Now i is ' + i);
console.log($obj);
switch (i) {
case 0:
//do something
break;
//and so on, or call a function with obj and i.
}
i++;
});
You can also add data-id
or data-anything
to your classes.
Upvotes: 0