1

I would like to get the last child in of a parent div.

Actually, I'm using this:

var els = '#first,#second,#third';

$(els).each(function () {

  $(this).children().last().addClass('memo');

});

It works great for divs with only 1 child, but when the last div is inside a div inside another div, it doesn't work.

var els = '#first,#second,#third';

$(els).each(function() {
  $(this).children().last().addClass('memo');
});
.memo {
  background-color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="first">First text
  <div>a</div>
</div>

<div id="second">Second text
  <img>b
</div>

<div id="third">Third text
  <div>Nested 1
    <div>Nested 2
      <img>c
    </div>
  </div>
</div>

How can I refer to the latest child?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 2
    Please write "here" in the child you mean. Last child is not a nested child. I updated your snippet to show what you are currently getting – mplungjan Jul 26 '21 at 14:37
  • 1
    Last child usually means the last child of siblings at the same level. Not the deepest one. – evolutionxbox Jul 26 '21 at 14:38
  • I think with last child you mean `img` or `parent of img` but in here they aren't children for `#third` they are descendants – JS_INF Jul 26 '21 at 14:43
  • 1
    Do you want the last element under each of `#first`, `#second`, `#third`? – Ruan Mendes Jul 26 '21 at 14:46

2 Answers2

2

Children are different from grandchildren/descendants. $.children only looks at immediate children.

For the behavior you want, you could find all descendants using * and use last() in this scenario, if you are looking for the last descendant in each of #first,#second,#third

It's also important to mention that this gets the last element child, not the last text node. jQuery is not able to deal with text nodes directly. Credits to @T.J. Crowder. See How do I select text nodes with jQuery?

$('#first,#second,#third').each(function () {
  $(this).find('*').last().addClass('memo');
});
img.memo {
  border: 3px solid red;
  padding: 5 px;
}

div.memo {
  border: 3px solid blue;
  padding: 5 px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="first">
  <div>a</div>
</div>

<div id="second">
  <img>b
</div>

<div id="third">
  <div>
    <div>
    <img>c
    </div>
  </div>
</div>
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
-3

You need remove the .last()

$(els).each(function() {
  $(this).children().addClass('memo');
});