Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: select an element's class and id at the same time?

People also ask

How do you select an element with ID and class?

CSS ID will override CSS Class properties. To select an element with a specific id, write a hash (#) character, followed by the id of the element.

Can you use ID and class together?

3) Can an HTML element have an id and class? Yes, any HTML element (like div, input, nav, body, etc) can have both “id” and “class” together and at the same time. The only difference here is that “id” can have only one unique value and “class” can have more than one.

Can I use both class and ID in CSS?

There are no rules in HTML that prevent you from assigning an element both an ID and a class. This <div> tag will be subject to the styles for the class backgroundOrange . In addition, it will also use the styles applied to the customDiv ID using an ID selector.

Should I use ID or class jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.


You can do:

$("#country.save")...

OR

$("a#country.save")...

OR

$("a.save#country")...

as you prefer.

So yes you can specify a selector that has to match ID and class (and potentially tag name and anything else you want to throw in).


Just to add that the answer that Alex provided worked for me, and not the one that is highlighted as an answer.

This one didn't work for me

$('#country.save') 

But this one did:

$('#country .save') 

so my conclusion is to use the space. Now I don't know if it's to the new version of jQuery that I'm using (1.5.1), but anyway hope this helps to anyone with similar problem that I've had.

edit: Full credit for explanation (in the comment to Alex's answer) goes to Felix Kling who says:

The space is the descendant selector, i.e. A B means "Match all elements that match B which are a descendant of elements matching A". AB means "select all element that match A and B". So it really depends on what you want to achieve. #country.save and #country .save are not equivalent.


It will work when adding space between id and class identifier

$("#countery .save")...


$("a.save, #country") 

will select both "a.save" class and "country" id.


In the end the same rules as for css apply.

So I think this reference could be of some valuable use.


How about this code?

$("a.save#country")