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
Christopher Lebbano
15,338 PointsI'm wanting to iterate through all children of an element, and then change that child's source attribute. jQuery
So after completing the first few sections of the jQuery basics, I wanted to come up with my own idea and complete a small project. I am trying to create a matching game.
I have a div with the id #wrapper, which is a flex container. Inside are 12 flex img elements. I want to change each img elements source to a specific image.
After googling, I found this piece of code:
$('#wrapper').children().each(function () { console.log($(this)); });
This will log all 12 img elements into my console, but I'm unsure on how to change the attributes of each one. Would I use maybe a for-loop instead somehow?
I've tried changing the console.log() code into something like $(this).attr("src", "myImage"); but that doesn't do anything.
Also, I have already generated an array of 12 unique random numbers that will correlate to the images I have. (This way, each time the page is loaded, each image will be randomly different).
1 Answer
Alexander Davison
65,469 PointsI'd use a for loop (like what you suggested).
Try something like this:
var wrapperChildren = $("#wrapper").children();
for (var i = 0; i < wrapperChildren.length; i++) {
$(wrapperChildren[i]).attr("src", "myImage");
}
Note: this is just demo code, I'm not sure if you want "src" to be "myImage" itself.
I hope this helps :)
Good luck! ~Alex
Christopher Lebbano
15,338 PointsChristopher Lebbano
15,338 PointsActually I figured it out already, check this out: This is only a band-aid fix until I start to add the code to keep the images hidden so that when clicked, it shows the real image (the animal)
Christopher Lebbano
15,338 PointsChristopher Lebbano
15,338 PointsHere is my website with the game in its current form.
Note, the game isnt fully function, it only randomly generates the tiles.
http://chrislebbano.com/game.html
Alexander Davison
65,469 PointsAlexander Davison
65,469 PointsGood job! I'm happy you made such a great website with my help :)