jqueryappendtoggleclass

On div click reveal list item with the same class


I need to be able to click on a div with a certain class and have it reveal a list item with that same class. I feel like that should be simple but I'm relatively new to jQuery. I was using this:

$('.minibox').on('click', function (){
    var txt = $(this).attr('name');
    $('ul').append("<li class='list'>"+txt+"</li>");
});

but I want to do it without the append method for several reasons. I think toggleClass is probably what I'm looking for, but I'm not sure exactly how to go about using it in this context. I also want to be able to click the '.minibox' again to remove the list item, hence why I'm assuming toggleClass is what I'm looking for.

Any help is appreciated <3


Solution

  • You can give your clicked element an attribute that points to the list element you would like to toggle. For instance if your list is like so

    <ul>
        <li class="first">something</li>
        <li class="second">something else</li>
    <li>
    

    Then you can indicate on your button the class you would like to toggle like so

    <button data-target-toggle="first">click me!</button>
    

    And then your click handler could read the data from the button and use that to select the list element

    $("button").click(function(){
        var targetClass = $(this).data("target-toggle");
        var targetElement = $("." + targetClass);
        //now you can do what you want to your targetElement, ie. show() or hide()
    }