If first child is iframe

1.4k Views Asked by At

I am trying to find out if the first child of one div is an iframe and if so, prepend it to another div. I am doing something very similar with images but they are easier to locate in that they will always be inside of the first p element. This is what is what I have that is throwing a children[0] is undefined error.

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

My HTML looks like this:

<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>
3

There are 3 best solutions below

0
Ram On

You can use first-child selector:

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

$(this).find(".post-excerpt") is jQuery object, and as jQuery object it has children function, not property

here is 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);
    }
});
1
Silvestre Herrera On

How about this?

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

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

Here, I made a JSFiddle for you. http://jsfiddle.net/uGAqY/