Over a million developers have joined DZone.

Styling the parent of an element

DZone 's Guide to

Styling the parent of an element

· Web Dev Zone ·
Free Resource

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;


Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}