I'm looping through divs to find the single 'active' class on a series of divs. I then want to get the data attribute from that div. I'm getting the data attribute fine but can't seem to pass it out of the function with a return. It logs undefined.
const getPostcardLink = () => {
console.log('getPostcardLink()...');
$('.postcard').each(function () {
if ($(this).hasClass('active')) {
const postcard = $(this).data('postcard');
console.log(postcard);
return postcard;
}
return 'error';
});
};
const getStampLink = () => {
console.log('getStampLink()...');
$('.stamp').each(function () {
if ($(this).hasClass('active')) {
const stamp = $(this).data('stamp');
console.log(stamp);
return stamp;
}
return 'error';
});
};
function updatePostcard() {
const postcard = `images/_${getPostcardLink()}.jpg`;
const stamp = `images/_${getStampLink()}.jpg`;
console.log(`${postcard} with ${stamp}`);
}
$(document).ready(() => {
updatePostcard();
});
Log returns...
getPostcardLink()...
p1
getStampLink()...
s1
images/_undefined.jpg with images/_undefined.jpg
getStampLinkdoes not return anything - there simply is noreturnstatement there.return stamp;returns from the.eachcallback, not fromgetStampLink. Similar for the other function.returndoes not cross function boundaries, it only returns from the function it is contained in."error"being returned? Substitute using.filter()for.each(), check if return value of.filter()has.lengthgreater than0