Home > Net >  Change outer ul background color when inner li has a class="selected"
Change outer ul background color when inner li has a class="selected"

Time:01-28

I have some menus with unordered list (ul):

<ul >
  <li>Button1</li>
  <li>Button2</li>
  <li >Button3</li>
  <li>Button4</li>
</ul>
<ul >
  <li>Button5</li>
  <li>Button6</li>
  <li>Button7</li>
  <li>Button8</li>
</ul>

and so on...

How i can change with jQuery the background color of outer ul when the inner li has ?

Thanks in advance.

CodePudding user response:

In this case, you can use method closest() or parent(). Here is an example using method closest().

Method closest() target a parent of any level relative to a child.

Method parent() only target the first level parent.

This is a jQuery solution:

$('li.selected').closest('ul').css('background', 'green');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul >
    <li>Button1</li>
    <li>Button2</li>
    <li >Button3</li>
    <li>Button4</li>
</ul>

<ul >
    <li>Button5</li>
    <li>Button6</li>
    <li>Button7</li>
    <li>Button8</li>
</ul>

CodePudding user response:

This would be a job for the "has" selector in CSS. Unfortunately, as of this writing, there's almost no browser support for it. Safari Technology Preview "cutting edge" browser has support, and that's just about it.

https://caniuse.com/?search=has

You can search for "css parent selector" to see how this has been a longstanding request among many web developers.

  •  Tags:  
  • Related