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

Repeat

I need this jQuery code to repeat if that makes sense.

if (jQuery("div.type:contains('Video')")) {
jQuery(".Code").hide();
jQuery(".Image").hide();
}

So I need

if (jQuery("div.type:contains('Video')")) {
jQuery(".Code").hide();
jQuery(".Image").hide();
}

if (jQuery("div.type:contains('Code')")) {
jQuery(".Video").hide();
jQuery(".Image").hide();
}

if (jQuery("div.type:contains('Image')")) {
jQuery(".Video").hide();
jQuery(".Code").hide();
}

But putting them after each other like that does not work...

3 Answers

Michael Hulet
Michael Hulet
47,912 Points

You could use one of JavaScript's loop syntaxes, depending on how you want it to repeat. If you want it to repeat a certain number of times, this will work:

for(var i = 0; i < /*Number of times you want your code to repeat here*/; i++){
  if (jQuery("div.type:contains('Video')")) {
  jQuery(".Code").hide();
  jQuery(".Image").hide();
}

Or, if you want it to repeat while a condition is true, this will work:

while(/*Condition*/){
  if (jQuery("div.type:contains('Video')")) {
  jQuery(".Code").hide();
  jQuery(".Image").hide();
}

Sorry I wasn't very clear. Each time it repeats it looks for a different word, and will do a different thing. As you can see, it looks for Video first, i it can't find that it will look for Code, followed by Image. If none exist it will do nohing?

Received answer else were. I needed to check the returned jQuery object for it's length:

if (jQuery("div.type:contains('video')").length) {
  jQuery(".Video").show();
  jQuery(".Code").hide();
  jQuery(".Image").hide();
}

See: http://stackoverflow.com/questions/24362171/jquery-look-for-a-specific-word for more help on this.