Highlight a simple string of numbers?

I have a javascript loop and want to highlight some numbers

for(i=0;i<=100;i++){
  $("#mydiv").append("<span>"+i+"</span>");
}

Now I want to select 1,5,9,13,17 ... every fourth, but I start with 1 and select it. every second is simple:

for(i=0;i<=100;i++){
  var bool = false;
  if(bool){
    $("#mydiv").append("<span>"+i+"</span>");
    bool = false;
  } else {
    $("#mydiv").append("<span class='highlight'>"+i+"</span>");
    bool = true;
  }
}

How can i do this?

+3
source share
7 answers

I am surprised that people recommend nth-child selectors for jQuery, but not just direct nth-child styling via CSS.

In your stylesheet:

#mydiv span:nth-child(4n-2) { background-color: yellow }
+4
source

you can do this with the nth-child selector. Check out this js script:

http://jsfiddle.net/pJZkL/

$(function(){
    var ap = "";
    for(i=0;i<=100;i++){
        ap+="<span class='nr'>"+i+", </span>";
    }
    $("p").append(ap);
});

The logic for this is now in CSS:

.nr{
    color: blue;
}
.nr:nth-child(4n-2){
    color: red;
}
+3
source
+2
for(i=0;i<=100;i++){
  if(i%4==1){
    $("#mydiv").append("<span class="highlight">"+i+"</span>");
  } else {
    $("#mydiv").append("<span>"+i+"</span>");
  }
}
+1

nth-child

$('#mydiv span:nth-child(4n+1)').addClass('highlight');
+1

I'm not sure I answered your question correctly. As far as I understand, the next cycle should help you.

var inc = 1;
for(i=0;i<=100;i++){
  if(i !== inc ){
    $("#mydiv").append("<span>"+i+"</span>");
  } else {
    $("#mydiv").append("<span class="highlight">"+i+"</span>");
    inc += 4;
  }
}
+1
source
 var pre = 0;
 for(i=0;i<=100;i++){
   if(i === 1 || (i-4) === pre ){
      $("#mydiv").append("<span class="highlight">"+i+"</span>");
      pre = i;
   } else {
      $("#mydiv").append("<span>"+i+"</span>");
   }
 }

That should do it. ive didn't check it though .. Cheers

0
source

All Articles