Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a style selector in jQuery?

Tags:

html

jquery

css

If I want to select every image which it's alt is Home for example, I can do something like this:

$("img[alt='Home']")

But how can I select every elements which their width CSS property is 750px for example in a single selector?

EDIT: If there is no such selector, is there any plugin, or any plans to do it in the next jQuery versions?

like image 200
Alon Gubkin Avatar asked Oct 26 '09 14:10

Alon Gubkin


People also ask

Does jQuery use CSS selectors?

jQuery uses CSS selector to select elements using CSS. Let us see an example to return a style property on the first matched element. The css( name ) method returns a style property on the first matched element. name − The name of the property to access.

What are the selectors in jQuery?

jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.

Which CSS selector engine is used by jQuery?

A selector engine is used to query a page's DOM for particular elements, based on some sort of query (usually CSS syntax or similar). Would search for and return all of the <div> elements on the page. It uses jQuery's selector engine to do that.

What is the use of CSS () method in jQuery?

jQuery css() Method The css() method sets or returns one or more style properties for the selected elements. When used to return properties: This method returns the specified CSS property value of the FIRST matched element.


2 Answers

Not necessarily a great idea, but you could add a new Sizzle selector for it :

$.expr[':'].width = function(elem, pos, match) {
    return $(elem).width() == parseInt(match[3]);
}

which you could then use like so:

$('div:width(970)')

That's going to be horrifically slow, though, so you'd want to narrow down on the number of elements you're comparing with something like :

$('#navbar>div:width(970)')

to only select those divs that are direct descendants of the navbar, which also have a width of 970px.

like image 103
Jonathan del Strother Avatar answered Sep 17 '22 13:09

Jonathan del Strother


var $images = $("img").filter(function() {
    return $(this).css('width') == '750px';
});

EDIT: There is no plugin I am aware of, or any plans to include such specific functionality. You can easily pluginify it yourself, such as (untested):

$.fn.filterByWidth = function(width) {
    var $images = $("img").filter(function() {
        return $(this).css('width') == width;
    });
    return $images;
};

Usage:

$images = $('#div img').filterByWidth('750px');
$images = $('#div img').filterByWidth('50%');
...etc...
like image 27
karim79 Avatar answered Sep 17 '22 13:09

karim79