Jquery 如果第一个孩子是iframe
我试图找出一个div的第一个子元素是否是iframe,如果是的话,将其前置到另一个div。我对图像做了一些非常类似的事情,但它们更容易定位,因为它们始终位于第一个p元素的内部。这就是我所知道的,抛出一个子项[0]是未定义的错误 我的HTML如下所示:Jquery 如果第一个孩子是iframe,jquery,parent-child,prepend,nodename,Jquery,Parent Child,Prepend,Nodename,我试图找出一个div的第一个子元素是否是iframe,如果是的话,将其前置到另一个div。我对图像做了一些非常类似的事情,但它们更容易定位,因为它们始终位于第一个p元素的内部。这就是我所知道的,抛出一个子项[0]是未定义的错误 我的HTML如下所示: <article class="post twelve columns centered"> <header class="post-header"> <h2 class="post-title
<article class="post twelve columns centered">
<header class="post-header">
<h2 class="post-title"><a href="#">Title</a></h2>
</header>
<section class="post-excerpt">
<iframe height="166" src="http://something.com"></iframe>
</section>
</article>
您可以使用第一个子选择器:
$(".post").each(function() {
if ( $(this).find(".post-excerpt iframe:first-child").length ) {
// ...
}
});
$this.find.post-extract是jQuery对象,作为jQuery对象,它有子函数,而不是属性
这是
这个怎么样
$('section.post-excerpt').each(function(){
var $el = $(this);
var $firstChild = $el.children().first();
if ($firstChild.prop('tagName') == 'IFRAME') {
alert('It is an iframe');
}
});
在这里,我为你做了一个JSFIDLE 实际上,这里的第一个答案非常有效,但被删除了。if$this.find.post摘录:第一个孩子是'iframe'。不知道为什么会被删除,但效果很好。我想我是想得太多了。你在哪里找到了接受数字参数的jQuery.children方法?我在jQuery文档中没有看到这一点。children接受一个选择器参数。@undefined-在这里缓存中间对象没有实际用途。这也可能是:如果$This.children.first.prop'tagName'='IFRAME'{…}
$(".post").each(function () {
var firstChild = $(this).find(".post-excerpt").children().get(0)
if (firstChild && firstChild.nodeName.toLowerCase() == 'iframe'){
var container = $("<div class='featured-video'></div>")
container.prepend(firstChild);
container.prependTo(this);
}
});
$('section.post-excerpt').each(function(){
var $el = $(this);
var $firstChild = $el.children().first();
if ($firstChild.prop('tagName') == 'IFRAME') {
alert('It is an iframe');
}
});