Using jQuery, how do you find only visible elements and leave hidden elements alone?

后端 未结 4 1057
忘掉有多难
忘掉有多难 2020-11-28 10:03

So I start with items 1-4:

Lorem
相关标签:
4条回答
  • 2020-11-28 10:41

    You can use the :not() selector for that and filter the results before going into the .each():

    $(".someDiv:not(:hidden)").each(function(){
    
    0 讨论(0)
  • 2020-11-28 10:42

    You can use the :visible selector to find only visible.

    $(".someDiv:visible").each(....);
    

    You can use the .not() selector to find only hidden.

    $(".someDiv").not(":visible").each(....);
    

    I think you can perform the same operation in your code with this one line.

    $(".someDiv").hide().find(".regular").show();
    

    Find all .someDiv and hide them, then find those with a .regular class and show them.

    0 讨论(0)
  • 2020-11-28 10:58

    You could use :visible selector to select the .someDiv that are visible.

    $(".someDiv:visible").each(function(){
     if($(this).hasClass("regular")){
        $(this).show();
      } else {
        $(this).hide();
      }
    });
    

    Here is another funny way utilizing the chaining :) and making it single line.

    $('.someDiv:visible').not($('.someDiv.regular:visible')).hide();
    
    0 讨论(0)
  • 2020-11-28 11:01

    You could do this two ways: You could add another class for the display: none elements and make them invisible via css, or you could find out the css property via jquery

    via css class

    html

    <div class="someDiv bold italic hidden" >Lorem</div>
    <div class="someDiv regular italic" >Lorem</div>
    <div class="someDiv bold hidden" >Ipsum</div>
    <div class="someDiv regular" >Ipsum</div>
    

    css

    .someDiv{
        display: block;
    }
    
    .hidden{
        display: none;
    }
    

    js

    $(".someDiv").each(function(){
      if($(this).hasClass("hidden")){
        $(this).show();
      } else {
        $(this).hide();
      };
    

    via jquery

    $(".someDiv:visible").each(function(){
     if($(this).hasClass("regular")){
        $(this).show();
      } else {
        $(this).hide();
      }
    });
    
    0 讨论(0)
提交回复
热议问题