Creating conditional statements for jQuery

I have a very newbie, so I apologize if the answer to this is obvious.

I use jQuery to switch the contents of the elements depending on whether the element was clicked. I was able to successfully implement the switch function.

Now I need to load it with the first two elements set for show () and the rest for hide (). I gave a unique class name to these first two subjects. I know that I can just do $('div.activeitem').show()and then hide you, but I would prefer to set the condition.

I am a beginner in jQuery, so I don’t know how to target these elements or their classes in a conditional expression. I searched google but was unsuccessful. I want a condition that asks if the div "newsinfo" also has a class "jopen", then show (), else hide ().

Thank you for your help. I have attached my code to help you understand the context of my question:

<script type="text/javascript">
                $(document).ready(function(){
                    // Here is where I'd like to implement a conditional
                    $('div.newsinfo').hide(); // this would be part of my else
                    $('h5.newstoggle').click(function() {
                        $(this).next('div').slideToggle(200);
                        return false;
                    });
                });
</script>
+3
source share
5 answers

How about just

$('div.newsinfo').each(function(){
    if($(this).hasClass('jopen')){
       $(this).show()
    }else{
       $(this).hide();
    }
 });
+4
source

there is a function hasClass(). Better to use toggleClass ().

For instance:

$('div.blocks').click(function(){
  $(this).toggleClass('class_name');
});

after the class of the first click is added, after the second - it is deleted ... etc. ^^

+1
source

JQuery hasClass.

.

if($(".selectableItem").hasClass("selected")){
    //remove selection
    $(".selectableItem").removeClass("selected");
}else{
    //remove the selected class from the currently selected one
    $(".selectableItem .selected").removeClass("selected");
    //add it to this one
    $(".selectableItem").addClass("selected");
}
+1

css jopen display: block, - display: none?

-

 .newsinfo {display: none}
 .jopen {display:block!important}
+1

Just use selectors. For example, if all divs with the class "newsinfo" are visible by default:

$("div.newsinfo:not(.jopen)").hide();

If all of them are hidden by default:

$("div.newsinfo.jopen").show();

+1
source

Source: https://habr.com/ru/post/1734605/


All Articles