Skip to content

Jquery nested LI elements inside tabbed content UL LI list

Im using tabbed content on my page (SEE MY FIDDLE)

Now the tabbed content makes use of <ul><li> elements to display the different tabs. Inside one of these tabs I would like to add a <ul><li> list however the list is not getting displayed correctly I suspect because:

  1. The jquery is effecting it
  2. It is nested inside another li elements

Any idea how I can fix this?

please look at fiddle to fully understand my question

Advertisement

Answer

You can use the >, child selector to refine the selectors to match only the <li> elements immediately under <ul id="tab">:

 ul#tab > li {
     display: none;
 }
 ul#tab > li.active {
     display: block;
 }
 $("ul#tab > li:nth-child(" + nthChild + ")").addClass("active");

https://jsfiddle.net/63og0jue/


Without >, the selectors will match any <li> descendant of <ul id="tab">:

<ul id="tab">
    <li><!-- ... --></li>
    <li>
        <!-- ... -->
            <li>one</li>
            <li>Two</li>
            <li>THree</li>
        <!-- ... -->
    </li>
    <li><!-- ... --></li>
</ul>

ul#tab li:nth-child(1), for example, matches both of these as the first-child of their respective parents:

<li>one</li>
<li>
    <p>HI There Enter personal Info</p>
</li>