Skip to content Skip to sidebar Skip to footer

Jquery If Object Is Present

I have a script that copies the text from an image's ALT-text and makes a caption box, and inputs the text. var alt = $('#hoejre p span img').attr('alt'); $('#hoejre p span img').a

Solution 1:

The size() method:

if ($("#hoejre p span img").size() > 0)
{
  var alt = $("#hoejre p span img").attr("alt");
  $('#hoejre p span img').after('<span></span>');
  $('#hoejre p span span').html('<strong>' + alt.replace('-', '</strong> <em>') + '</em>');
}

Solution 2:

jQuery selectors return an array.

You can check whether it contains any elements with the native JS Array.length property. Base your if on whether the length is >0.

Solution 3:

You can check how many objects a jQuery selector returns with .size()

Check fcalderan's answer, which suggests using the .length property instead. It has the same result, but is potentially faster.

For example you can do the following:

var$imgs = $("#hoejre p span img");
if( $imgs.size() > 0 ) {
    var alt = $imgs.attr("alt"); 
    $('<span></span>').html('<strong>' + alt.replace('-', '</strong> <em>') + '</em>')
                      .insertAfter( $imgs );
}

Post a Comment for "Jquery If Object Is Present"