a dubois
a dubois

Reputation: 51

Is there a more concise way to select elements within ancestors elements that contain certain classes

I'm selecting a lot of elements in my code based on whether or not an ancestor element contains classes, and wondered if there was a more concise way to do it.

For instance, to select all <p> and <blockquote> elements nested inside a <div> or <main> element, which has the class 'orange', I'm writing.

$('main.orange p, div.orange p, div.orange blockquote, main.orange blockquote').css('background-color', 'orange');

This accomplishes what I want, but it's a little tedious writing out div.className element, main.className element for all the elements I want to select. Is there a way to select all <p> elements nested in any ancestor with the class 'orange'?

Upvotes: 1

Views: 40

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

You can consider skipping the tag names in case if you don't have other tags using the same class. Also, using a cartesian way will help you minimise this selector:

$(".orange").find("blockquote, p");

This is one of the best simplified methods. Or if you are specific about the tags:

$("main.orange, div.orange").find("blockquote, p");

The above is an exact simplification, while I tend to use more of the first style than the above style, as long as the class names aren't used by other elements and I don't want to select them.

Also, I noticed that you are setting some CSS property on the element. I would kindly ask you to please use jQuery (or JavaScript) only for interaction and use CSS fully for presentation.

Have a class, say .js-orange and apply it to all those elements. For them, in the CSS, try adding this:

.orange-applied {background-color: orange;}

And then in jQuery, just do:

$(".js-orange").addClass("orange-applied");

This way, you will be able to either toggleClass or removeClass programmatically and one of the best approaches.

Upvotes: 2

Related Questions