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.
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.
Share Improve this question asked Apr 21, 2015 at 6:55 Rick HelstonRick Helston 7634 gold badges12 silver badges21 bronze badges 1-
Use this Selector:
jQuery('img:not([title!=""][title])').each(function() { jQuery(this).attr('title', jQuery(this).attr('alt')); })
– Kailash Yadav Commented Apr 21, 2015 at 7:16
7 Answers
Reset to default 4jQuery('img').each(function () {
$this = $(this);
if (!$this.attr('title') && $this.attr('alt')) {
$this.attr('title', $this.attr('alt'));
}
})
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'));
}
JS
jQuery('img').each(function() {
var jq=jquery(this)
var title= jq.attr('title');
if(title == undefined)
jq.attr('title', jq.attr('alt'));
});
You can also use the setter version of .attr() like
jQuery('img').attr('title', function () {
if (!this.title) {
return this.alt
}
})
Demo: Fiddle
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
.
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.
$('img').attr('alt','image here'); $('img').attr('title','pany name')