How to Apply css class on runTime


Tags: jquery,css

Problem :

I am new to jQuery. I want to apply css class to my <li> element but it's not working. Can anyone help me?

My markup is:

<ul class='change'>
    <li>companyName</li>
    <ul id='uid'>
        <li onClick='callTest()'>subcompany</li>
        <li onClick='callTest()'>subcompany</li>
        <li onClick='callTest()'>subcompany</li>
    </ul>

  <ul id='uid'>
        <li onClick='callTest()'>subcompany2</li>
        <li onClick='callTest()'>subcompany2</li>
        <li onClick='callTest()'>subcompany2</li>
    </ul>
    </li>
</ul>

My problem is when I call the callTest() method, I want to change the background color for that <li> i am trying this way not working:

$('#uid li').click(function () {
    console.log("call lil...'");
    $(this).addClass('selected').siblings().removeClass('selected');
})

It's working fine but the first I selected subcompany it's applied selected class for that and now I selected subcompany2 for this also applied selected class but on this time I want to remove subcompany class. How can I do this?



Solution :

Modify your HTML this way:

<ul class='change'>
    <li>companyName</li>
    <ul id='uid'>
        <li>subcompany</li>
        <li>subcompany</li>
        <li>subcompany</li>
    </ul>
</ul>

and ADD this JS this way:

$('#uid > li').each(function () {
    $(this).on("click", function() {
        console.log("call lil...'");
        $(this).addClass('selected').siblings().removeClass('selected');
    });
});

    CSS Howto..

    How to debug CSS/Javascript hover issues

    jQuery hide() and show() not working as expected

    How to manage css files the best way

    How to combine several hover elements in JS/Jquery

    HTML - How do I insert a tag into each line of a
     block without hard coding?

    How to use :not selector in CSS?

    How to bring parent div front?

    Responsive CSS, How to make clock maintain position with image on resize

    QuickSand Script not showing correctly in IE 7

    how can i add style with CSS to