开发者

JQuery hide Class if other class is visible or shown

开发者 https://www.devze.com 2023-01-27 21:43 出处:网络
Found similar questions but nothing that covers exactly what I need.I kept it simple in my example and I want to use JQuery.

Found similar questions but nothing that covers exactly what I need. I kept it simple in my example and I want to use JQuery.

I have two classes. I want to hide th开发者_如何学Pythone "filter" div if the "category" div is shown on page load. There are currently NO styles associated with either class. I believe I am pretty close but it doesn't work.

<script language="text/javascript">
if(!$(this).hasClass("category")){
$('filter').css('display', 'none');
}
</script>

<div class="category">By Category</div>
<div class="filter">By Custom Filter</div>

Thanks in advance!


Use .length to test if an element is present.

Use .hide() & .show() to show and hide elements.

And finally, you want the code to run only when the page has finished loading, so you want to wrap it all in $(document).ready().

So something like this should work best:

<script language="text/javascript">
    $(document).ready(function() {
        //following code will hide all elements with a class of 'filter'
        //if any elements with a class of 'category' are found
        if($('.category').length){
            $('.filter').hide();
        }
    });
</script>

<div class="category">By Category</div>
<div class="filter">By Custom Filter</div>

HTHs,
Charles


Change the selector to $('.filter')


var $filter = $(".filter");
var $category = $(".category");

$category.is(":visible") ? $filter.hide() : $filter.show();


jQuery

$('div').each(function() {
    if ($(this).hasClass("category")) {
        $('.filter').css('display', 'none');
    }
});

or just:

if ($('.category').length) {
    $('.filter').css('display', 'none');
}


 <div class="category">By Category</div>
 <div class="filter">By Custom Filter</div>

Assuming by "shown on page load" you mean rendered and not the show/hide visibility.

$('.category').each(function(){
    $('.filter').hide();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消