D.R.
D.R.

Reputation: 21194

Selector to find first matching level of elements

Having the following structure:

<ul>
    <li>
        <div><span class="node">Content1</span></div>
    </li>
    <li>
        <div><span class="node">Content2</span></div>
    </li>
    <!-- but also: -->
    <li>
        <div><span class="node">Content3</span>
            <ul>
                <li>
                    <div><span class="node">Content on 2nd level</span></div>
                </li>
            </ul>
        </div>
    </li>
</ul>

Now I want to select all span elements with the CSS class node which are on the first level of the hierarchy. How to do that without also matching the last span on level 2?

Edit: The div tags are just for demo purposes. They can change to span or even be nested within another div. I don't want to get a brittle CSS selector out of this (web testing), so I do not want to use direct child selectors. Furthermore, I cannot make changes to the HTML code myself.

Upvotes: 2

Views: 122

Answers (3)

BoltClock
BoltClock

Reputation: 723658

You will need to start from the parent of the top-level ul and work your way down using child selectors. For example, assuming the parent element is identified by #parent:

#parent > ul > li > div > span.node

If the hierarchy of elements between the li and the span.node is not fixed, then things get a little more complicated. In order to avoid matching the inner span.node elements, you will need to make some assumptions about the markup, since a simple descendant selector like the following will always return every span.node since every nested list occurs as a descendant of your top-level li elements:

#parent > ul > li span.node

Upvotes: 2

hahaha
hahaha

Reputation: 1037

Fix/Ammend your html code, simple is better.

Working fiddle

<div><span class="node test">Content2</span></div>

add 2 class names to your span

.node.test {
    color: red;
}

points to the right span

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You can use > selector:

#parent > ul > li  .node

Or, if you haven't parent id:

ul > li :not(ul) .node

Upvotes: 2

Related Questions