CSS Parent Selector jQuery Workaround

This question comes up a bunch of times on coding forums: How can I style/select the parent of an element with a specific class? Now, most of the time this question is posed looking for a CSS solution. Unfortunately, CSS2/3 doesn’t offer a parent selector. CSS4 has it written as potential addition to the CSS core, but that could change as CSS4 is still in the development phase.

There is a simple workaround for those that are interested in a lightweight jQuery solution. I’m offering the jQuery solution, mainly because most of the sites that are developed already include a jQuery library. So without further ado, here’s the code (this would go into your main jQuery (document).load function):

$('.childclass').parent(this).addClass('parentclass');

What this basically does is from start to finish: finds elements with a class, then finds the parent of that class, then adds a class to the parent. You may already have a class for that parent element, but this will add another class so you can style it. You could also add the CSS directly in the script, using .css(), but I find it easier to have my CSS in my CSS file rather than spread out over multiple places.

Hopefully someone will come across this on the interwebs and find it useful.

About Chris

Chris is the senior web/graphic designer with The Simons Group. He enjoys diving into code and developing solutions to uncommon problems. He is an avid bicycle commuter and enjoys playing and recording music.

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*