Aurimas
Aurimas

Reputation: 23

How to select parent and not child in CSS?

I have a menu which looks something like this:

<div class="myclass" >
    <ul>
        <li>
        <li>        <------- select parent li and not child li
        <li>
            <ul>
                <li> <------ then select only child li
                <li>
            </ul>
        <li>
        <li>
        <li>
    </ul>
</div>

I need to style parent and child menus seperetely but I can't seem to get how to select them and style seperetely. Any help appreciated! :)

Upvotes: 0

Views: 2298

Answers (3)

CK Wolfe
CK Wolfe

Reputation: 51

Try this one:

for parent

.myClass > ul > li

Sample:

$( ".myClass > ul > li" ).css( "color", "green" ); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myClass" >
    <ul>
  <li>Coffee</li>
  <li>
    <ul>
    <li>Tea</li>
    <li>Black Tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>
</div>

for child

.myClass > ul > li > ul > li

Sample:

$( ".myClass > ul > li > ul > li" ).css( "color", "green" ); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myClass" >
    <ul>
  <li>Coffee</li>
  <li>
    <ul>
    <li>Tea</li>
    <li>Black Tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>
</div>

Upvotes: 0

Corentin Branquet
Corentin Branquet

Reputation: 1576

For parent you do like this :

.myclass > ul > li

And for child:

.myclass > ul > li > ul > li

Upvotes: 0

user663031
user663031

Reputation:

Select only higher-level <li>:

.myclass > ul > li

Select lower-level <li>:

.myClass > ul > li > ul > li

The key here is using the direct child selector >. See https://developer.mozilla.org/en-US/docs/Web/CSS/Child_selectors.

Upvotes: 2

Related Questions