最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do you loop over each div within a container that has a specific class? - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 6

try 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'));
});
发布评论

评论列表(0)

  1. 暂无评论