Over a million developers have joined DZone.

Styling the parent of an element

· Web Dev Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

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 by Stormpath—offering a complete, pre-built User Management API for building web and mobile applications, and APIs. Download our new whitepaper: "Build Versus Buy: Customer Identity Management for Web and Mobile Applications".


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

{{ parent.tldr }}

{{ parent.urlSource.name }}