I have multiple divs that have the class of 'flag-container'. My goal is to (using jquery) loop over each of these divs, find the image within it (each div has a single child image) and then return the ID of that image. How would I be able to achieve this and loop over these divs one by one? (I'm not very good with JS loops)
I have multiple divs that have the class of 'flag-container'. My goal is to (using jquery) loop over each of these divs, find the image within it (each div has a single child image) and then return the ID of that image. How would I be able to achieve this and loop over these divs one by one? (I'm not very good with JS loops)
Share Improve this question asked Mar 5, 2015 at 11:21 Jack O'ConnorJack O'Connor 3343 silver badges19 bronze badges 4- 3 Try this: api.jquery./each – Billy Moat Commented Mar 5, 2015 at 11:22
- api.jquery./each – Alan Dunning Commented Mar 5, 2015 at 11:23
- 2 Why would you need to retrieve the ID of these images? You'd have better to explain your expected final behaviour and provide all relevant code in question itself – A. Wolff Commented Mar 5, 2015 at 11:23
- There is no relevant code, hence why I asked the question. – Jack O'Connor Commented Mar 5, 2015 at 11:35
4 Answers
Reset to default 6try each()
$( ".flag-container" ).each(function( index ) {
console.log($(this).find('img').attr('id'));
});
Try this out:
$('div.flag-container > img').each(function() {
console.log($(this).attr('id'));
});
As mentioned in the ments and in @Stewartside's answer, the above selector will only work if the img
is a direct descendent of your flag-container
div.
If not, you should use the more general selector $('div.flag-container img')
.
You could also do
$('div.flag-container').each(function() {
console.log($(this).find('img').attr('id'));
});
Try jQuery's each()
function.
$('div.flag-container img').each(function() {
console.log($(this).attr('id'));
});
Read more here: https://api.jquery./jquery.each/
Check this fiddle for your answer : http://jsfiddle/rLbkyeha/
$(".flag-container").each(function(){
alert( $(this).children('img').attr('id'));
});