views:

82

answers:

4

I got a series of divs like this:

<div class="message" style="padding-left: 0px;">...</div>
<div class="message" style="padding-left: 20px;">...</div>
<div class="message" style="padding-left: 20px;">...</div>
<div class="message" style="padding-left: 40px;">...</div>
<div class="message" style="padding-left: 20px;">...</div>

And I would like to make a selector that would get me the divs with padding greater then 20px.

Would it be possible with just using jquery? Or I should modify my html tree and add some attribute that would distinguish those elemenents with high padding value?

+1  A: 

You can use filter for this.

var elems = $('div.message').filter(function (){
               return parseInt($(this).css("padding-left"),10) > 20;
            });

alert ( elems.length );

or using each you can do something like this

$(function(){
    var elems = new Array();
    $("div.message").each(function(){
        if(parseInt($(this).css("paddingLeft"), 10) > 20 )
        {
            elems.push($(this));
        }           
    });

    alert ( elems.length );
});
rahul
+4  A: 

You can use a filter with a custom function.

$('div.message').filter(function(){
     return parseInt($(this).css('padding-left')) > 20;
});

p.s. I don't sure what .css('padding') > 20 will return, I'm guess I need to test it....

Mendy
`$(this).css('padding-left') > 20;` will return `false` for a padding-left value of `20px` because it's not a number.
Andy E
So `parseInt('20px')` will do the job. but what about if you want a grater padding of ANY side? in other words what `.css('padding')` will return? do it does the job, or you should include this logic in the function too? that's what I was said, I need to look on it.
Mendy
@Mendy: If you look at the docs, you'll see that shorthand properties are not supported by `.css()`. However, if the shorthand property `padding` was set on a div element, accessing `.css('padding-left')` would return the correct, computed style anyway.
Andy E
A: 

You could use filter()

var col = $('div').filter(function ()
{
    return parseInt($(this).css("padding-left")) > 20;
});

or you could create your own selector:

$.expr[':'].myselector = function(obj, index, meta, stack){
   return parseInt($(obj).css("padding-left")) > 20;
};
var col = $("div:myselector");
Andy E
+1  A: 

You could use $('.message') selector, and then loop through your elements finding the one with .css padding-left set to anything you want.

Second solution, involves usage of custom selectors.

You can modify this code I took from my blog:

$.extend($.expr[':'], {
    redOrBlue: function(o) {
        return ($(o).css("color") == "red") 
               || ($(o).css("color") == "blue");
    }
});

Usage:

$('div:redOrBlue')
rochal