enc
enc

Reputation: 121

How to get last children class jquery

I try to distinguish last children in div. I have something like below. I want to check which is last, children1 or children2.

This script doing just if, no matter what class is at the end.

if ($('.parent').children('.children1').last()) {
  alert("children1");
  // do something
} else if ($('.parent').children('.children2').last()) {
  alert("children2");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <div class="children1"></div>
  <div class="children2"></div>
  <div class="children1"></div>
  <div class="children2"></div>
</div>

Upvotes: 0

Views: 88

Answers (2)

zer00ne
zer00ne

Reputation: 43870

Although ugly IMHO you can use the .attr() method. The following function accepts two parameters:

  1. parentSelector: CSS selector string of the parent element.

  2. targetSelector: CSS selector string of the elements that need to be targeted.

const last = (parentSelector, targetSelector) => {
  return $(parentSelector).children(targetSelector).last().attr('class');
}

console.log(last('.parent', '.c1, .c2'));
<section class="parent">
  <div class="c1"></div>
  <aside class="c2"></aside>
  <figure class="c1"></figure>
  <section class="c2"></section>
  <div class="c1"></div>
  <div class="c3"></div>
  <div class="c2"></div>
  <ol class='c3'>
    <li class='c1'></li>
    <li class='c2'></li>
  </ol>
</section>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

To achieve this you can use :last to get the last child element, then is() or hasClass() to determine which class it has:

var $lastChild = $('.parent div:last');
if ($lastChild.is('.children1')) {
  alert("children1");
  // do something
} else if ($lastChild.is('.children2')) {
  alert("children2");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <div class="children1"></div>
  <div class="children2"></div>
  <div class="children1"></div>
  <div class="children2"></div>
</div>

Upvotes: 2

Related Questions