0

I have to run some code only when a particular element in the DOM (img tag) exists, if not then I want to run some other code. Below is what I have till now.

Original Code:

 ed.on('blur', function (e) {
        var iFrame = $('iframe');

        $("img[src*='blob']", iFrame.contents()).each(function (i) {
            var originalUrl = $(this).prop('src');
            var that = $(this);
            // SOME CODE

           );
        });

Below is what I want

ed.on('blur', function (e) {
    var iFrame = $('iframe');
******If ( img[src*='blob' exists in the iFrame )********
    $("img[src*='blob']", iFrame.contents()).each(function (i) {
        var originalUrl = $(this).prop('src');
        var that = $(this);
        // SOME CODE
       );
    }   
    else
    {
       // Do something else
    }
});

So basically if I cannot find $("img[src*='blob']" in the iframe I want to run some other code. Please guide me.

Unbreakable
  • 7,776
  • 24
  • 90
  • 171

3 Answers3

1

You'll want to check the number of elements in the jQuery object (jQuery.length):

if($('img[src*="blob"]').length > 0) {
  // your code
}
Daerik
  • 4,167
  • 2
  • 20
  • 33
1

So instead of just doing the each, store it into a variable and check the length.

var imgs = $("img[src*='blob']", iFrame.contents());
//var imgs = iFrame.contents().find("img[src*='blob']"); //how I would write it
if (imgs.length) {
    imgs.each(...)
} else {
    ...
}
epascarello
  • 204,599
  • 20
  • 195
  • 236
0
$("img[src*='blob']").length > 0
Eric
  • 9,870
  • 14
  • 66
  • 102