0

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.

hasmai
  • 45
  • 9

4 Answers4

2

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"});
msapkal
  • 8,268
  • 2
  • 31
  • 48
  • Your solution was perfect.I think checking this question also can give a good idea. http://stackoverflow.com/questions/251814/jquery-and-organized-code/255222#255222 – mr. Sep 02 '16 at 13:51
1
if ($(this).hasClass('toggle')) {

    $('.toggle > span')
        .first().css({
            // something...
        })
        .end().eq(2).css({
            // something...
        })
        end().last().css({
            // something...
        });

}
0

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.

vaso123
  • 12,347
  • 4
  • 34
  • 64
0

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... }
    }
}
Artem Gorlachev
  • 597
  • 4
  • 9
  • Sorry I missed to add span in it but I mean, want to know jQuery code, not SCSS. Thanks anyway. – hasmai Sep 02 '16 at 13:41
  • Sorry, didn't understand your question correctly. I didn't know beauty ways for your question. I`m trying to use additional classname to element and styling childrens with css. – Artem Gorlachev Sep 02 '16 at 13:45