user1763295
user1763295

Reputation: 1098

Selecting an element that doesn't have a child with a certain class

The structure of my HTML is like so

<div>
    <div>
        <h1>Something</h1>
    </div>
    <div>
        <h1 class='Handle'>Something</h1>
    </div>
</div>

In the event that the div > div does not have a child with the class "Handle" I want the the div > div to have the style cursor:move;. How would I go about doing this in pure CSS, is it even possible?

Upvotes: 47

Views: 58013

Answers (4)

Ali Sheikhpour
Ali Sheikhpour

Reputation: 11096

Is this enough for this purpose?

div > div:not(:has(.Handle)):not(:empty) {
    cursor: move;
}
<div>
    <div>
        <h1>Something</h1>
    </div>
    <div>
        <h1 class='Handle'>Something</h1>
    </div>
</div>

Upvotes: 1

Damien
Damien

Reputation: 1538

:not(:has())

Note: Limited support for old browsers.

The example below demonstrates the combination of the :not() and :has() pseudo-classes to select elements that do not have a specified child.

div:not(:has(p)) {
  background: powderblue;
}
div:not(:has(p)):hover {
  color: blue;
  background: azure;
}
<div>
  <h1>Does Not Have a Paragraph</h1>
</div>
<div>
  <h1>Has a Paragraph</h1>
  <p>Paragraph</p>
</div>

As of March 2024, :has() is supported by most modern browsers. However, Firefox only recently implemented support for :has in release 121 (dated 2023-12-19.) So, use with caution if old browsers are used by clients. :not() has been supported since 2015 by most browsers.

Alternatively, jQuery supports the :has() selector.

Upvotes: 46

koningdavid
koningdavid

Reputation: 8095

There is no parent selector in CSS, so what you are asking is not possible. What you can do is put the cursor:move on every h1 that doesnt has the class "Handle" by using the attribute selector.

h1:not([class=Handle]) {
    cursor:move;
} 

http://jsfiddle.net/4HLGF/

Another option is to adjust your HTML, and move your h1 on the same level as the div.

<div>
    <h1>Something</h1>
    <div>
        dragable content
    </div>
    <h1 class='Handle'>Something</h1>
    <div>
        non dragable content
    </div>
</div>

Now you can do the same check on the h1, and target the div that comes after it.

h1:not([class=Handle]) + div {
    cursor:move;
}

http://jsfiddle.net/4HLGF/2/

Upvotes: 5

Leo T Abraham
Leo T Abraham

Reputation: 2437

Try

div > div h1:not([class=Handle]) {
    cursor:move;
} 

Upvotes: -3

Related Questions