0

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
8
  • 3
    getStampLink does not return anything - there simply is no return statement there. Commented Mar 6, 2017 at 20:28
  • 3
    return stamp; returns from the .each callback, not from getStampLink. Similar for the other function. return does not cross function boundaries, it only returns from the function it is contained in. Commented Mar 6, 2017 at 20:28
  • How do you handle case of "error" being returned? Substitute using .filter() for .each(), check if return value of .filter() has .length greater than 0 Commented Mar 6, 2017 at 20:35
  • @Felix Kling: That helps me fix my code. Many thanks! Commented Mar 6, 2017 at 20:48
  • I'm going to explore @guest271314's filter suggestion also. Commented Mar 6, 2017 at 20:48

1 Answer 1

1

Use .filter() and same pattern at getStamp()

const getPostcardLink = () => {
  console.log('getPostcardLink()...');
  let elems = $('.postcard').filter(function () {
    return $(this).hasClass('active')
  });
  if (elems.length) {
      const postcard = elems.data('postcard');
      console.log(postcard);
      return postcard
  }
  return "error"
};

function updatePostcard() {
  let cLink = getPostcardLink();
  let sLink = getStampLink();
  if (cLink !== "error") const postcard = `images/_${cLink}.jpg`;
  if (sLink !== "error") const stamp = `images/_${sLink}.jpg`;
  if (postcard && stamp) console.log(`${postcard} with ${stamp}`);
}
Sign up to request clarification or add additional context in comments.

1 Comment

You could also pass a selector to filter, like $('.postcard').filter('.active')

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.