Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Trying to loop through nth-child

Trying to loop through captions but this doesn't seem to work. I've played around and I know that if I replace the i with an actually number it will give me the correct response. I feel like this is a syntax issue.

for (i = 1; i <= 12; i++){ var captionText = $("a:nth-child(i)").attr("title"); console.log(captionText); }

2 Answers

Steven Parker
Steven Parker
243,318 Points

Your "i" above is just a character in the string.

To replace it with the variable's value, you could use concatenation:

$("a:nth-child(" + i + ")")

Or you could use string interpolation:

$(`a:nth-child(${i})`)

But since you're already using jQuery, you might make the whole thing more compact by using .each() directly on the collection instead of a loop:

$("a").each(function () {
  console.log($(this).attr("title"));
});

That worked thank you