0

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>
WordPress Mike
  • 448
  • 2
  • 6
  • 21
  • Actually, the first answer here worked perfectly but it was deleted. `if($(this).find(".post-excerpt :first-child").is('iframe'))`. Not sure why it was deleted but it works just fine. I believe I was over thinking it. – WordPress Mike Oct 19 '13 at 02:59

3 Answers3

4

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/

  • @undefined - No real use for caching the intermediate objects here. This could also be: `if ($(this).children().first().prop('tagName') == 'IFRAME') {...}` – jfriend00 Oct 19 '13 at 03:48
3

You can use first-child selector:

$(".post").each(function() {
    if ( $(this).find(".post-excerpt iframe:first-child").length ) {
       // ...
    }
}); 
Ram
  • 143,282
  • 16
  • 168
  • 197
1

$(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);
    }
});
krasu
  • 2,037
  • 23
  • 22
  • Where did you find a jQuery `.children()` method that takes a numeric argument? I don't see that in the jQuery doc. `.children()` takes a selector argument. – jfriend00 Oct 19 '13 at 03:40