Friday, May 6, 2011

Is it possible to select all floats on a page with JQuery ?

I am trying to select all elements that have CSS computed style float:left or float:right. I see attribute selectors available in the JQuery documentation, however I am interested in CSS properties not attributes.

Possible use cases for such a feature would be to select say all display:none elements on a page.

From stackoverflow
  • One idea would be to apply the floating style via CSS then you could select on the class name and do a show/hide as necessary.

     <style>
        .right { float: right; }
        .left { float: left; }
     </style>
    
     <div class='left'>...</div>
     <div class='right'>...</div>
    
      $('.left,.right').hide();
    
    Jed Schmidt : $('.left.right') would be empty in this case, since you're looking for elements with both classes. Did you mean $('.left, .right')?
    tvanfosson : The interesting bit is that I had it that way originally and then must have misread the documentation. Yes, the comma needs to be there.
  • This should do the trick without class hacking:

    $("*").filter( function() {
        return /^(left|right)$/.test( $(this).css("float") )
    })
    

    By the way, jQuery already has a nice way to find all display: none elements:

    $(":hidden")
    
  • Creating new selectors is kind of fun, so I did that:

    Usage:

    :hasCssAttr(property, value ...)

    Property is the css property you would like use to compare

    value is the value(s) you would like to match against (you can have more than one)

    $(':hasCssAttr(float, left)').css('float', 'right');
    

    The source Luke:

    $.expr[':'].hasCssAttr = function(objNode, intStackIndex, arrProperties, arrNodeStack) {
      var arrArguments = arrProperties[3].split(','); 
      var cssPropVal = $(objNode).css(arrArguments[0]); // need for speed
      for (var i = 1 ; i < arrArguments.length ; i++)
        if (cssPropVal == arrArguments[ i ].replace(/^\s+|\s+$/g,""))
            return true;      
      return false;
    }
    

    Basically, this selects any ol' css property. I suppose you could eliminate the loop if you only wanted one value, kind of unnecessary. Also, I wonder if it might be more interesting to do this in an eval so you could do numerical comparisons. Anyway. There it is.

    Props to Ben for helping me out.

    KyleFarris : +1 for making your own flexible selector. I always prefer flexible solutions when possible.

0 comments:

Post a Comment