user3671322 user3671322 - 1 year ago 143
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

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

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

Answer Source

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


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download