0

I wondering how can I addClass to the furthest parent from li, I tried this and it working fine but I'm feel it's a bad logic, isn't it?

$('li').each(function() {
  $(this).click(function() {
    $(this).parent().parent().parent().parent().parent().parent().addClass('myClass');
  });
});
.myClass {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div> <!-- I want to add class to this parent -->
  <div>
    <div>
      <div>
        <div>
          <ul>
            <li><a>Click</a></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</div>

I want to something like closest() that work for children, is there a way to access grand parent? in this example I forced to write parent() six times!

void
  • 36,090
  • 8
  • 62
  • 107
Jack The Baker
  • 1,781
  • 1
  • 20
  • 51

2 Answers2

1

Fetch the .last() among all of the .parents() of the element.

$('li').each(function() {
  $(this).click(function() {
    $(this).parents('div').last().addClass('myClass');
  });
});
.myClass {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div> <!-- I want to add class to this parent -->
  <div>
    <div>
      <div>
        <div>
          <ul>
            <li><a>Click</a></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</div>
void
  • 36,090
  • 8
  • 62
  • 107
0

Use $(this).parents([optional]).eq(n)

Update :

Here are some properties if we console.log($(this).parents()) and console.log($(this).parents('div')), the flexibility of .eq(n) is maybe not every time we want the outermost one:

$(this).parents()

{
  "0": <ul>…</ul>,
  "1": <div>…</div>,
  "2": <div>…</div>,
  "3": <div>…</div>,
  "4": <div>…</div>,
  "5": <div class="myClass">…</div>,
  "6": <body>…</body>,
  "7": <html>…</html>,
  "length": 8,
  ...

$(this).parents('div')

{
  "0": <div>…</div>,
  "1": <div>…</div>,
  "2": <div>…</div>,
  "3": <div>…</div>,
  "4": <div class="myClass">…</div>,
  "length": 5,
 ...

$('li').each(function() {
  $(this).click(function() {
     $(this).parents().eq(5).addClass('myClass');
     // Or 
     // $(this).parents('div').eq(4).addClass('myClass');
     console.log($(this).parents('div'));
  });
});
.myClass {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div> <!-- I want to add class to this parent -->
  <div>
    <div>
      <div>
        <div>
          <ul>
            <li><a>Click</a></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</div>
Carr
  • 2,691
  • 1
  • 19
  • 27