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').after('<span></span>');
$('#hoejre p span span').html('<strong>' + alt.replace('-', '</strong> <em>') + '</em>');
This works great, when there IS an image. But when there aren't any images, the script fails in IE7.
How can I wrap the VAR with an IF sentence.
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').after('<span></span>');
$('#hoejre p span span').html('<strong>' + alt.replace('-', '</strong> <em>') + '</em>');
This works great, when there IS an image. But when there aren't any images, the script fails in IE7.
How can I wrap the VAR with an IF sentence.
Share Improve this question asked Nov 12, 2010 at 11:38 curly_bracketscurly_brackets 5,59815 gold badges62 silver badges103 bronze badges4 Answers
Reset to default 3why call a method when you could just look at length property?
if ($imgs.length) {
... /* one or more images exist */
}
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>');
}
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.
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 );
}