3

I want to make li element in alternate color but only those have a attribute data-filetype="image".

As soon as I add a new li without adding data-filetype attribute, my color sequence fails.

Link to JSBin is here

HTML Code:

<ul> 
 <li data-filetype="image">PNG Image</li><!-- It should be RED -->
 <li data-filetype="image">PNG Image</li><!-- It should be ORANGE -->
 <li>Normal Link</li><!-- After adding this li color sequence breaks -->
 <li data-filetype="image">PNG Image</li><!-- It should be RED -->
 <li data-filetype="image">PNG Image</li><!-- It should be ORANGE -->
</ul>

CSS:

ul li[data-filetype="image"]:nth-child(2n){color:orange}
ul li[data-filetype="image"]:nth-child(2n+1){color:red}
vaibhav silar
  • 2,905
  • 2
  • 15
  • 18
  • but is there any alternative way? – vaibhav silar Jul 03 '14 at 09:09
  • Don't think so with pure css – Pete Jul 03 '14 at 09:10
  • 1
    No, you cannot do this with CSS as the `nth-child/nth-of type` **only** applies to elements (with a common parent) and is not related to classes or any other attributes. See - http://stackoverflow.com/questions/5428676/nth-child-doesnt-respond-to-class – Paulie_D Jul 03 '14 at 11:14

1 Answers1

0

Using jquery you can get the alternate Row color even if extra element added. Have a look at DEMO.

/JQuery Code/

$(document).ready(function(){

$("li[data-filetype='image']:even").css({'color':'red'});
$("li[data-filetype='image']:odd").css({'color':'blue'});
$("li:not([data-filetype='image'])").css({'color':'white'});
});
Kheema Pandey
  • 9,977
  • 4
  • 25
  • 26
  • This works, but I am looking for CSS solution. Now the question is that if its working through JQuery then why its not working using CSS only. – vaibhav silar Jul 03 '14 at 10:29