Skip to content Skip to sidebar Skip to footer

Select Div With Specific Width

Quick Question: How to select a div with certain width. For example we have 10 div in one page, I want to select the one that has 200px width and do something. Thanks a lot.

Solution 1:

What JCOC611 said:

var $theDivs = $('div').filter(function() { return $(this).width() === 200; });

That'd get you a jQuery object with all matching (200px) divs in it. Might not be the fastest thing in the world; it'd probably be better to more directly and explicitly identify your page elements, if you can.

Solution 2:

You can also extend jQuery's pseudo-selectors, like this:

// Extend jQuery ":" pseudo selector to include a width() test

$.extend( $.expr[':'], {
    width: function ( element, index, selectorMatches ) {
        var expr = selectorMatches[3].match( /^\s*([<>]?={0,1})?\s*(\d+)\s*$/ ),
            elementWidth = $( element ).width(),
            targetWidth, comparisonOperator;

        if ( ! expr ){
            console.log( "invalid expression" );
            returnfalse;
        }

        comparisonOperator = expr[1] || "==";
        targetWidth = parseInt( expr[2] );

        returneval( elementWidth + comparisonOperator + targetWidth );
    }
});


// Valid expressions are:// :width( 200 ), :width( = 200 ), :width( == 200 )// :width( > 200 ), :width( >= 200 )// :width( < 200 ), :width( <= 200 )
$('div:width( 200 )').hide();

This IMHO is a lot more fun than using filter(), but jsperf shows it to be just a little bit slower (4% slower).

Here's a jsFiddle that you can play around with.

Post a Comment for "Select Div With Specific Width"