How can I toggle sibling child elements?

为君一笑 提交于 2020-01-25 06:53:08

问题


I want to be able to click an item and toggle its classes. This is working as expected. Also, when the item is clicked a child element's class toggles (in order to hide with CSS). This is working as expected.

I want to click any sibling to one of these items and have the others' classes toggle. This is working as expected. Here is where I am stuck: I want to be able to click an item and have the sibling's child element's class toggle - this is NOT working as I had hoped.

I've used some help articles to get this far using jquery, but my newb knowledge isn't getting me all of the way there.

This codepen has the HTML and JS that I'm trying flush out: https://codepen.io/deejmer/pen/zgRYyj

$(".feature-expand a.card").click(function(e){
    e.preventDefault();
    $(this).parent().toggleClass( "col-12").toggleClass( "col-md-6");
    $(this).parent().siblings().removeClass( "col-12").addClass("col-md-6");
    $(this).find(".hidden-item").toggleClass( "shown");
});

Thanks in advance for helping a jquery newb!


回答1:


Just all hidden elements except this one.

let thisHiddenItem = $(this).find(".hidden-item");
$('.hidden-item').not(thisHiddenItem).removeClass('shown');
thisHiddenItem.toggleClass("shown");

Demo

If necessary, limit scope by targeting the containing feature element:

$(this).closest('.some-wrapper-el').find('.hidden-item').removeClass('shown');

Protip: You can combine your class toggler: .toggleClass( "col-12 col-md-6")



来源:https://stackoverflow.com/questions/57379312/how-can-i-toggle-sibling-child-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!