Link to home
Start Free TrialLog in
Avatar of mike99c
mike99c

asked on

How to hide last <li> using JQuery but not the nested <li>s

I have a simple nested menu example and I would like to hide the last top level <li> which in the below example is the <li> containing the menu "Sustainability report". Unfortunately my JQuery script seems to affect the nested <li> tags as well which is not what I want.

Incidentally I cannot add an ID to the last <li> which I realise would solve the problem but a solution needs to be applied to the HTML as shown without any modifications.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Hide last li</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

<script type='text/javascript'>
//<![CDATA[
$(function() {

  $('#main-navigation ul li:last-child').hide();
	  
});
//]]>
</script>

</head>

<body>
<div id="main-navigation">
  <ul>
    <li>
      <a>About us</a>
      <div>
        <ul>
          <li>
            <a>Our Vision</a>
            <ul>
              <li><a href="#">Vision statement</a></li>
            </ul>
          </li>
        </ul>
        <ul>
          <li><a>Report and Accounts</a>
            <ul>
              <li><a href="#">Chief Executive's Statement</a></li>
              <li><a href="#">Documents</a></li>
              <li><a href="#">History</a></li>
            </ul>
          </li>
        </ul>
      </div>
    </li>
    <li><a>Our work</a>
      <div>
        <ul>
          <li><a>Current Projects</a>
            <ul>
              <li><a href="#">Project 1</a></li>
              <li><a href="#">Project 2</a></li>
              <li><a href="#">project 3</a></li>
            </ul>
          </li>
        </ul>
        <ul>
          <li><a>Sectors</a>
            <ul>
              <li><a href="#">Aviation</a></li>
              <li><a href="#">Energy</a></li>
              <li><a href="#">Flood Alleviation</a></li>
            </ul>
          </li>
        </ul>
      </div>
    </li>
    <li><a>Sustainability report</a>
      <div>
        <ul>
          <li><a title="Menu 1">Menu 1</a>
            <ul>
              <li><a href="#" title="Menu 1 - 1">Menu 1 - 1</a></li>
              <li><a href="#" title="Menu 1 - 2">Menu 1 - 2</a></li>
            </ul>
          </li>
        </ul>
      </div>
    </li>
  </ul>
</div>
</body>
</html>

Open in new window

Avatar of Duy Pham
Duy Pham
Flag of Viet Nam image

Maybe this could help to solve your case:

$('#main-navigation ul:first-child li:last-child').hide();

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Rainer Jeschor
Rainer Jeschor
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mike99c
mike99c

ASKER

Thanks this worked perfectly. The use of ">" for immediate children did the trick.