asdf
asdf

Reputation: 1

check if element exists within parent element

I'm embedding and appending a youtube video to a div by using the href value and adding it to youtube.com/embed/ +hrefvariable. I just need some guidance in how to check if the youtube video is already in the div, to not run the click function that appends it there. I'm thinking using .length() with the parent div?

Here's the appending function:

$(function () {
    $(".youtube").click(function (a) {
        a.preventDefault();
        a = '<iframe src="http://www.youtube.com/embed/' + $(this).attr("href") + '?&iv_load_policy=3&autoplay=1#t=0m12s&rel=0" frameborder="0" allowfullscreen ></iframe>';
        $("#currentvid").html(a);
        $("#currentvid").animate({
            opacity: 1
        }, 1E3);
        return !1
    })
});

Upvotes: 0

Views: 875

Answers (3)

Steve
Steve

Reputation: 8640

var iframe_ele = $("#currentvid").find('iframe');
if (iframe_ele.length > 0) {
    ...
}

Upvotes: 0

Justin Bicknell
Justin Bicknell

Reputation: 4808

You could do this if ($("#currentvid iframe").length) return; at the top of your click function. I would also recommend storing $('#currentvid') in a var.

Upvotes: 1

Horen
Horen

Reputation: 11382

If you want to check if the iframe already exists or not use:

if ($("iframe").length == 0){
   //iframe doesn't exist yet. Append it.
}

If you have multiple iframes, give it an id and check for that.

Upvotes: 0

Related Questions