Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to change the background color of even elements in the list?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 352
    Comment on it


    We can change the background color of the members of the list using filter() function in jQuery.

    Note: The filter() function matches each element with the supplied selector and  creates a subset of the matching elements.

    Let us understand with the help of an example:

    Following is the list of elements from which I have to change the background color of the elements at even  position:

     <ul>
            <li>list item 1</li>
            <li>list item 2</li>
            <li>list item 3</li>
            <li>list item 4</li>
            <li>list item 5</li>
            <li>list item 6</li>
        </ul>
    

    Let us take a button that will change the color of the elements at even  position onclick.

     <input type="button" onclick="ChangeColor()" />
    

    Now write the following function inside the script tag:

    function ChangeColor() {
    
                $("li").filter(":even").css("background-color", "red");
            }

    This will change the color of the 1,3,5 element as the index starts from 0, So elements at index 0,2 and 4 will get their background color changed.

     

                                                        Hope it helps.... Happy Coding !

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: