How to add a class in a class by clicking on it, leaving only it with that class?

7

For example:

  • I have more than ul with li ;
  • If I click on a% of% of the first li it has to add a class;
  • If I click on a ul of the second li , it adds that same class. Only which does not interfere with the list of the first ul ;
  • To get more clarified, it is as if each ul is a group of radio button, where only one per group is marked.

    Any ideas?

        
    asked by anonymous 11.02.2014 / 13:10

    5 answers

    4

    Here is the link to the complete example: link

    Basically the following code does is:
    1) When the document is loaded add click event to each li.
    2) When it is clicked, remove from all li of the ul closest to the selected class
    3) Add selected class to the li that was selected

    $( document ).ready(function() {
        $('li').click(function() {
            $(this).closest('ul').find('li').removeClass('selected');
            $(this).addClass('selected');
        });
    });
    
        
    11.02.2014 / 13:23
    2

    You should first remove the class from any li within ul :

    $('#id_ul li').removeClass('minha_classe');
    

    Then you add in the li that the event was clicked:

    $(this).addClass('minha_classe');
    

    This must be done within click in li .

    Complete example

    $("#id_ul li").on("click", function(){
        $('#id_ul li').removeClass('minha_classe');
        $(this).addClass('minha_classe');
    });
    
        
    11.02.2014 / 13:19
    2

    Use .siblings() so vicê will only change elements that are within the same level of ul

    $( document ).ready(function() {
        $('li').click(function() {
            $(this).siblings().removeClass('selected');
            $(this).addClass('selected');
        });
    });
    

    It's a short code and exactly fulfills your need.

    It's basically the same code as the Serhiy just by changing the use of .closest() and .find() you use only .siblings() and manipulates all elements that are at the same level as the selected one.

        
    11.02.2014 / 14:28
    1

    First, classify your% s of% s. Let's name them ul . And the class of the selected items will be tipoRadio .

    $(function() {
        $(".tipoRadio").on("click", "li", function() {
            var ul = $(this).parent(".tipoRadio");
            ul.children("li").removeClass("selecionado");
            $(this).addClass("selecionado");
        });
    });
    

    Fiddle

        
    11.02.2014 / 13:20
    0

    To complement, and if you want to get more knowledge on this subject, I suggest you access this link site, there are some free courses which will be very useful to you.

        
    11.02.2014 / 14:51