2013-10-19 55 views
0

我想知道一個div的第一個孩子是否是iframe,如果是的話,請把它加到另一個div上。我正在做一些與圖像非常相似的東西,但它們更容易定位,因爲它們始終位於第一個元素的內部。這就是我所拋出的children[0] is undefined錯誤。如果第一個孩子是iframe

 $(".post").each(function() { 

    if($(this).find(".post-excerpt").children[0].nodeName.has('iframe').length){ 

      $(this).prepend("<div class='featured-video'></div>"); 

      $(this).find(".post-excerpt").children[0].nodeName.has('iframe').prependTo($(this).find(".featured-video")); 
    } 
}); 

我的HTML看起來像這樣:

<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> 
+0

其實,這裏的第一個答案完美,但它被刪除。 if($(this).find(「。post-excerpt:first-child」)。('iframe'))''。不知道爲什麼它被刪除,但它工作得很好。我相信我在想這件事。 –

回答

3

您可以使用first-child選擇:

$(".post").each(function() { 
    if ($(this).find(".post-excerpt iframe:first-child").length) { 
     // ... 
    } 
}); 
1

$(this).find(".post-excerpt")是jQuery對象,並作爲jQuery對象具有children函數,而不是財產

這裏是jsFiddle

$(".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); 
    } 
}); 
+0

你從哪裏找到一個採用數字參數的jQuery'.children()'方法?我沒有看到在jQuery文檔中。 '.children()'接受一個選擇器參數。 – jfriend00

+0

是的,你是對的 – krasu

4

這個怎麼樣?

$('section.post-excerpt').each(function(){ 
    var $el = $(this); 
    var $firstChild = $el.children().first(); 

    if ($firstChild.prop('tagName') == 'IFRAME') { 
     alert('It is an iframe'); 
    } 
}); 

在這裏,我爲你做了一個JSFiddle。 http://jsfiddle.net/uGAqY/

+0

+1正確緩存和使用'.prop()'。 – undefined

+0

@undefined - 在這裏沒有真正的用於緩存中間對象的用法。這也可以是:'if($(this).children()。first()。prop('tagName')=='IFRAME'){...} – jfriend00

相關問題