Conditional Alert Message with CSS Adjacent Selector

There are many CSS selectors we can apply style through but selectors like Pseudo Elements, Adjacent, etc. do the trick to reduce efforts on JavaScriptThis article would focus on how we can use CSS adjacent selector to show an alert message box, conditionally. Using adjacent selector, we can target very next element at the same level of elements sequence.

Syntax of CSS Adjacent

#table-header + .alert-message{
    display: block;

The Discussion

I recently worked on an AngularJS project with a Manish Sharma, where on-page content search was the main feature. Also user can filter data-rows based on various criteria. Below I am attaching a draft version of the design to make my words more clear.

Rough UI - Concept IFIU
Rough Project Design (image-1)

As you can see, above screenshot has a header with number of checkbox filters and a dropdown (for even more available filters). The next is a search textbox and below that we have a table with heading and data in rows.

Now, if we follow the above image and search for the text term "Content 4", then we will be getting not data in a table. And as per the requirement, this is when we have to show an alert box/message. Below screenshot will help you to understand the scenario:

Rough UI no data found - Concept IIU
No Data Found (image-2)

The Solution

Let's think on HTML structure first. As we have to target using CSS adjacent selector, we must have all elements (that we want to play with) at the same level. We can count on 3 elements for our needs.

  1. Table Header (#table-header) - image-1
  2. Table Data (#data) - image-1
  3. Alert Message Box (.alert-message) - image-2

Recall the syntax once and get clear idea that why we have to use all elements sequentially. If you have any doubts, please post a comment below.


As of now, I am embedding same kind of DEMO where search functionality created using another jQuery plugin but the purpose is as same to understand the approach.

See the Pen GoWxGX by Kushal Jayswal (@kutec) on CodePen.

AngularJS completely hide the element if the search criteria doesn't match but here I have other demo which hides child elements. So I had to use :empty selector to achieve the goal. But we are not going to focus on that now and I will try to put another demo with AngularJS soon.

If you have any query or doubts, please comment below OR you can share better examples as well.