Search code examples
jqueryclassindexingchildren

jQuery cannot find children indexes


I have one of ul tag which include another child ul tag. I'm trying to access child tag but it's not working properly.

// php
$parent_index = 1; // Parent Index, li of ul 
$child_index = 2; // Child Index, li of ul


$("ul li").eq($parent_index).addClass("red")
  .children("ul li").eq($child_index).addClass("red");
.red {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul> 
  <li>Brazil
    <ul><li>1st</li><li>2nd</li><li>3rd</li></ul></li> 
  <li>Germany
    <ul><li>1st</li><li>2nd</li><li>3rd</li></ul></li> 
  <li>Italy
    <ul><li>1st</li><li>2nd</li><li>3rd</li></ul></li> 
  <li>Russia
    <ul><li>1st</li><li>2nd</li><li>3rd</li></ul></li> 
</ul> 

If then the text of "3rd" had to change red color in Germany ul tag.

// php
$parent_index = 1; // Parent Index, Germany
$child_index = 2; // Child Index, 3rd

However it does not work at all. Am I wrong method in my jQuery?


Solution

  • The problem is your selectors, ul li will select all li in your page instead of just the parent one.

    You can use a more specific selector, like add a class to the parent element then use that to select the elements

    // php
    $parent_index = 1; // Parent Index, li of ul 
    $child_index = 2; // Child Index, li of ul
    
    // Jquery 
    $(".parent > li").eq($parent_index).addClass("red").find("ul li").eq($child_index).addClass("red");
    .red {
      color: red
    }
    
    .red .red {
      background-color: blue
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    // html
    <ul class="parent">
      <li>Brazil
        <ul>
          <li>1st</li>
          <li>2nd</li>
          <li>3rd</li>
        </ul>
      </li>
      <li>Germany
        <ul>
          <li>1st</li>
          <li>2nd</li>
          <li>3rd</li>
        </ul>
      </li>
      <li>Italy
        <ul>
          <li>1st</li>
          <li>2nd</li>
          <li>3rd</li>
        </ul>
      </li>
      <li>Russia
        <ul>
          <li>1st</li>
          <li>2nd</li>
          <li>3rd</li>
        </ul>
      </li>
    </ul>