如何使用 jquery 检查 div 中的最后一个孩子是否是



>假设我有一个由用户输入的输入动态填充的div。你如何检查div中的最后一个孩子是否是<img>.下面的 html 代码给出了我想要实现的目标的想法。

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

要获取您使用的元素的最后一个子元素 如何在jQuery中选择最后一个子元素?

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

要测试元素是否为img请使用.is('img') .

然后将它们组合成$('div').children().last().is('img')

或者,您可以将parent > child选择器与:last-child结合使用

$("div > img:last-child").length > 0
<div id="myKey">
    <p>Some text</p>
    <p>Some text</p>
    <p>Some text</p>
    <img src='example.jpg' > /* Check if this is img element*/
</div>

和代码:

var lastChild = jQuery("#myKey").children().last();
var isImg = lastChild.is("img"); //true or false

您可以使用:last-child选择器并获取选择器的length或使用.is()方法,如底部代码

if ($("div > img:last-child").length > 0) 
// Or
if ($("div > img").is(":last-child"))

if ($("div img").is(":last-child"))
    console.log("last child is img");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <p>Some text</p>
    <p>Some text</p>
    <p>Some text</p>
    <img src='example.jpg' >
</div>

这应该可以解决问题:

$( "div img:last-child" )

var last = $('div').children().last();
if ( last.is( "img" ) ) {
    alert("image");
}
<div>
    <p>Some text</p>
    <p>Some text</p>
    <p>Some text</p>
    <img src='example.jpg' > /* Check if this is img element*/
</div>

最新更新