Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining a class selector and an attribute selector with jQuery

People also ask

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.

Can you use CSS selectors in jQuery for selecting elements?

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.

Are all CSS selectors compatible with jQuery?

Starting from jQuery 1.9, virtually all selectors in the level 3 standard are supported by Sizzle (its underlying selector library), with the following exceptions: jQuery cannot select any pseudo-elements as they are CSS-based abstractions of the document tree that can't be expressed through the DOM.

How do I use multiple selectors in CSS?

Example# When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your style sheet. Use a comma to separate multiple grouped selectors. So the blue color applies to all <div> elements and all <p> elements.


Combine them. Literally combine them; attach them together without any punctuation.

$('.myclass[reference="12345"]')

Your first selector looks for elements with the attribute value, contained in elements with the class.
The space is being interpreted as the descendant selector.

Your second selector, like you said, looks for elements with either the attribute value, or the class, or both.
The comma is being interpreted as the multiple selector operator — whatever that means (CSS selectors don't have a notion of "operators"; the comma is probably more accurately known as a delimiter).


I think you just need to remove the space. i.e.

$(".myclass[reference=12345]").css('border', '#000 solid 1px');

There is a fiddle here http://jsfiddle.net/xXEHY/


This code works too:

$("input[reference=12345].myclass").css('border', '#000 solid 1px');

This will also work:

$(".myclass[reference='12345']").css('border', '#000 solid 1px');