Find all images with no ALT and set filename to ALT.

JS Code Snippets/Functions

Javascript

/* Copy and paste this to global.js */

var imgs = document.querySelectorAll('img[alt=""]'); //collects all empty alt images

for(var i = 0; i < imgs.length; i++) {
	var imgurl = imgs[i].src;
	var filename = imgurl.substring(imgurl.lastIndexOf('/')+1);
	var trimedFilename = filename.replace(/(\.[^/.]+)+$/, "");
	var titleAlt = trimedFilename.replace(/[_-]/g, " ");
	imgs[i].setAttribute("alt", titleAlt);
	imgs[i].setAttribute("title", titleAlt);
}

jQuery

$('img[alt=""]').each(function(){
	const src_ = $(this).attr('src');
	const filename_ = src_.substring(src_.lastIndexOf('/')+1);
	const trimedFilename_ = filename_.replace(/(\.[^/.]+)+$/, "");
	const titleAlt_ = trimedFilename_ === "" ? trimedFilename_.replace(/[_-]/g, " "):filename_;

	$(this).attr('alt',titleAlt_);		
});

Leave a Reply

Your email address will not be published. Required fields are marked *