user10677233
user10677233

Reputation:

CSS select element only when it contains n elements

I have an html structure similar to this:

<div class="node">
  <div class="children">
    <div class="nodes"></div>
    <hr/>
  </div>
  <div class="name">This is the node's name!</div>
</div>

I want the div.node > div.name to have a green background but only when the div.node > div.children > div.nodes is empty.

I wanted to count all elements in the div.node > div.children and if there are only two (div.node > div.children > div.nodes and div.node > div.children > hr), I want the following div.node > div.name to have a green background.

The selector I imagined would be this: div.node > div.children:contains(2) + div.name buit obviously this doesn't work.

Any ideas to solve this issue?

Edit:

I was able to remove the div.node > div.children. Now my html structure looks like this:

<div class="node">
  <div class="nodes"></div>
  <hr/>
  <div class="name">This is the node's name!</div>
</div>

With this structure I can use the :empty selector:

div.node > div.nodes:empty + hr + div.name {
  background-color: green;
}

Upvotes: 1

Views: 264

Answers (1)

ciekals11
ciekals11

Reputation: 2155

There is no such thing in CSS (sadly) but you have JS.

document.querySelectorAll('.node').forEach(node => {
  const childrensCount = node.querySelectorAll('.children').length;

  if(childrensCount === 2) {
    node.querySelector('.name').style.backgroundColor = 'green';
  }
});
<div class="node">
  <div class="children">
    <div class="nodes"></div>
    <hr/>
  </div>
  <div class="name">This is the node's name!</div>
</div>
<div class="node">
  <div class="children">
    <div class="nodes"></div>
    <hr/>
  </div>
  <div class="children">
    <div class="nodes"></div>
    <hr/>
  </div>
  <div class="name">This is the node's name!</div>
</div>
<div class="node">
  <div class="children">
    <div class="nodes"></div>
    <hr/>
  </div>
  <div class="children">
    <div class="nodes"></div>
    <hr/>
  </div>
  <div class="children">
    <div class="nodes"></div>
    <hr/>
  </div>
  <div class="name">This is the node's name!</div>
</div>

PS
as cloned mentioned in his comment event better approach will be to set a class like .bg-green to name when element is rendered before sending it to user browser

Upvotes: 1

Related Questions