user3671322 user3671322 - 4 months ago 26
HTML Question

How to check if last child in a div is <img> with jquery?

Assume I have a div that is dynamically populated by input entered by user.
How do you check if the last child in a

div
is a
<img>
. The html code below gives an idea of what I'm trying to achieve.

<div>
<p>Some text</p>
<p>Some text</p>
<p>Some text</p>
<!-- Check if this is img element -->
<img src='example.jpg' >
</div>

Answer

To get the last child of an element you use How to select last child element in jQuery?:

$('div').children().last()

To test if an element is an img you use .is('img').

Then you combine them to $('div').children().last().is('img')

Or you can use the parent > child selector in combination with :last-child

$("div > img:last-child").length > 0