简体   繁体   中英

change background every <li> generated

I have a list that is generated by javascript every time someone adds an item: the html looks like this:

<ul class="items-listed-rc">
    <li>1 generated by javascript</li>
    <li>2 generated by javascript</li>
    <li>3 generated by javascript</li>
    <li>4 generated by javascript</li>
    ...
</ul>

currently all are with the blue background, I would like the

  • 2 and 4 have different background and so continued .. Blue, red, blue, red, blue, red ...

  • You can use CSS selector nth-child:

    .items-listed-rc li:nth-child(even){
        background:red;
    }​
    

    Edit

    As jay Harris mentioned, the CSS selector nth-child is not supported by IE8 and below. You can use jQuery for that:

    $(document).ready(function() {
        $(".items-listed-rc li:nth-child(even)").addClass("even");
    });
    

    CSS:

    .items-listed-rc li.even{
        background:red;
    }
    

    If you need to do this using javascript, you could do

    $(".items-listed-rc li:odd").css("background-color", "red")
    $(".items-listed-rc li:even").css("background-color", "blue")
    

    Otherwise css options are better as don't require adding extra js code, just we aware of selectors compatibility.

    It really depends on how you're adding the list items. Probably the best way, as others have mentioned, is to use the nth-child() pseudo class , but iE8 and below doesn't support it.

    If you're generating with JS, you could use a counter or the modulus operator .

    var ul = document.getElementById("items");
    for (var i = 1; i < 6; i++){
        var li = document.createElement("li");
    
       // Set odd/even class name 
        li.className = (i%2 == 1 ? "odd" : "even" );
    
        li.appendChild(document.createTextNode("#"+i+" Created with JavaScript"));
        ul.appendChild(li);
    }
    

    http://jsfiddle.net/daCrosby/xBcFQ/

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM