So use case is this that i have a block where i am printing images inside a similar content with similar class Now i want to change the alt just by adding book cover at the end but when i run the code book cover is rendered more than once is there a way i can fix this?
/* changing alt tags of featured items */
$(".featured-item").each( function () {
var alt_val = $(this).find('img').attr("alt");
console.log(alt_val);
$(this).find('img').attr("alt", "Book cover:" alt_val "");
});
CodePudding user response:
use one variable (me) for next usings.
Add a class "done-with-alt" after done your alt attribute. If the element has class "done-with-alt" continue.
Check and skip: if ($(this).hasClass("done-with-alt")) return true;
Done after : $(this).addClass("done-with-alt");
Your new code can be:
/* changing alt tags of featured items */
$(".featured-item").each( function () {
var me = $(this);
if (me.hasClass("done-with-alt")) return true;
var alt_val = me.find('img').attr("alt");
console.log(alt_val);
me.find('img').attr("alt", "Book cover:" alt_val "");
me.addClass("done-with-alt");
});
If jQuery can not update your element (.featured-item), you can wrap this interval around and check that every 100 ms for about 1000 ms long:
var myInterval = setInterval(function(){
/* changing alt tags of featured items */
$(".featured-item").each( function () {
var me = $(this);
if (me.hasClass("done-with-alt")) return true;
var alt_val = me.find('img').attr("alt");
console.log(alt_val);
me.find('img').attr("alt", "Book cover:" alt_val "");
me.addClass("done-with-alt");
});
},100);
setTimeout(function(){
clearInterval(myInterval);
},1000);
Not good code because the interval/checks have to be stopped. So this code use a triggered timeout to clear the interval (which must be done hopefully after 1000 milliseconds).