3
votes
jQuery('img').each(function() {
    jQuery(this).attr('title', jQuery(this).attr('alt'));
})

How can I modify the code above so that it only applies the title attribute from alt if it doesn't already have a title attribute? In other words, if the image already has a non-empty title attribute, this code shouldn't execute.

6
Use this Selector: jQuery('img:not([title!=""][title])').each(function() { jQuery(this).attr('title', jQuery(this).attr('alt')); })Kailash Yadav

6 Answers

4
votes
jQuery('img').each(function () {
    $this = $(this);
    if (!$this.attr('title') && $this.attr('alt')) {
        $this.attr('title', $this.attr('alt'));
    }
})
0
votes

By using a condition to check if the 'alt' attribute exists:

if (jQuery(this).attr('alt') != undefined) {
    jQuery(this).attr('title', jQuery(this).attr('alt'));
}
0
votes

JS

jQuery('img').each(function() {
    var jq=jquery(this)
    var title= jq.attr('title');
     if(title == undefined)
       jq.attr('title', jq.attr('alt'));
});
0
votes

You can also use the setter version of .attr() like

jQuery('img').attr('title', function () {
    if (!this.title) {
        return this.alt
    }
})

Demo: Fiddle

0
votes
jQuery('img:not([title!=""][title])').each(function() {
    jQuery(this).attr('title', jQuery(this).attr('alt'));
})

You can use this selector which will take care of all img tags with or without title attribute exists and if exists, it should be empty.

0
votes

This should do the trick.

jQuery('img').each(function () {
    var $el = jQuery(this),
        title = $el.attr('title'),
        alt = $el.attr('alt');
    if (title === undefined || title == '' || alt === undefined || alt == '')
        return;

    $el.attr('title', alt);
});

The code above will skip all images that have an empty or undefined title or alt attribute.