1

I understand that selecting by the class attribute in jquery is one of the most performant ways of selecting elements. We apply the class attribute on all elements to represent the CSS style. I'd like to select a subset of these elements using jquery class selector.

So, should I be applying multiple styles to the element - one to represent the css style and the other on solely for jquery selection purposes?

1
  • This what I do to group the elements that need to use the same jQuery event. Commented Nov 16, 2011 at 15:47

4 Answers 4

1

You can use multiple classes to describe different "information" of an element. For example Wordpress does that with the "body" element, it assigns classes that represent the browser type etc.

Another way to do that is to assign a class / id to a parent of the elements you want to select, such that you can do this:

jQuery('#parent_of_group').find('.class_name');
Sign up to request clarification or add additional context in comments.

Comments

1

Selecting elements by class attribute value certainly is not "one of the most performant ways" to select an element. On the contrary: jQuery's Sizzle is very slow by comparison, especially when a class simple selector is involved.

Instead, one of the more efficient ways to select an element is by ID. You should do this if there is only one relevant element, as IDs must be unique in a document. It would probably be best then if you used the now-ubiquitous document.getElementById() method, and only created a jQuery object if it is absolutely necessary.

But you should check first whether it is necessary to select elements at all. DOM APIs have several other, more compatible entry points to refer to an element object, among them this (in event-handler attribute values and event listeners), event (in event-handler attribute values), and element collections and node lists. Event bubbling also is ubiquitous by now, although not all events bubble in all implementations.

Comments

0

Elements can have multiple classes

class="firstClass secondClass thirdClass"

..if that's what you're asking

Comments

0

So, if I understand it correctly, you want to select a subset of elements with a certain class (class1), again filtered by another class (class2)?

jQuery('.class1.class2');
// or
jQuery('.class1').filter('.class2');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.