HTML5 Zone is brought to you in partnership with:

Younes has posted 1 posts at DZone. View Full User Profile

Styling the parent of an element

05.12.2014
| 4293 views |
  • submit to reddit

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:

jQuery('selector-for-your-valid-input')
    .closest('selector-of-the-parent-style')
    .addClass('valid').removeClass('error');

jQuery('selector-for-your-invalid-input')
    .closest('selector-of-the-parent-style')
    .addClass('error').removeClass('valid');


In your CSS:

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


Published at DZone with permission of its author, Younes Ouadi.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)