skip to Main Content

Consider this example, a,b,c,d are just random tags. The d-tag marked with with class="select" are the ones I want to select. Of course, I dont have a class on them.

The rule should be: Select the highest-level occuring descendant only, so from outhermost to innermost – the first time the d-tag occures.

<container>
  <a>
    <b>
      <a>
        <c><d class="select"></d></c>
      </a>
    </b>
  </a>
  <a>
    <d class="select">
      <a>
        <c><d><a><d></d></a></d></c>
      </a>
    </d>
  </a>
</container>

Can this be done in CSS?

2

Answers


  1. Unfortunately, this is not possible with CSS alone.
    CSS doesn’t allow you to directly detect the hierarchy of nodes in the DOM and access the first occurrence of an element within that hierarchy. You can only make selections based on the relative position of elements in the DOM.

    Login or Signup to reply.
  2. You could select the ds which are not descendants of another d – d:not(d d)

    This snippet has replaced the a tag as that has other meaning and also has added a character into each element so we can see what is being changed.

    x,
    a,
    b,
    c,
    d {
      color: black;
    }
    
    d:not(d d) {
      color: red;
    }
    <container>
      <x>x
        <b>b
          <x>x
            <c>c<d class="select">select</d></c>
          </x>
        </b>
      </x>
      <x>x
        <d class="select">select
          <x>x
            <c>c
              <d>d
                <x>x
                  <d>d</d>
                </x>
              </d>
            </c>
          </x>
        </d>
        </a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search