Over a million developers have joined DZone.
Platinum Partner

Styling the parent of an element

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

There are many situation where you would need to style the parent of given element. Let's image a form that contains some input elements. After validation, you would like to highlight the inputs that contain valid data and those that contain invalid data. Styling the input itself would give an ugly result and to get a nice result, you would need to style the parent of the inputs. This was a situation I have faced with inputs that have been enhanced with jQueryUI.

In web Dev, the most appropriate method for styling is CSS. The issue is that CSS doesn't provide any selector that will allow you to select the parent of your inputs.

As such, you might be tempted by using 'jQuery.closest()' to manipulate directly the style of the parent. Technically speaking, that is possible. However, it is a bad option in case your need to allow customization of your development.

The ideal solution I see consist of:
1) Use 'jQuery.closest()' to add a class to the parent of your inputs
2) Style the added class using CSS

In your code:



In your CSS:

.valid {
    border: 1px solid green;
.error {
    border: 1px solid red;

The Web Dev Zone is brought to you in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}