Crossman
Crossman

Reputation: 278

iterating specific elements

I know in jQuery you can iterate through all elements of a specific type with:

$(function() {
   $('img').each(function() {
   });
});

what if I want to itterate through elements in a specific div, I tried using the ('#div' > a) selector but that doesn't seem to work

Upvotes: 0

Views: 89

Answers (3)

GautamD31
GautamD31

Reputation: 28763

Try with

$(function() {
      $('#div_id img').each(function() {
           alert($(this).attr('src'));
      });
});

Upvotes: 1

tiredone
tiredone

Reputation: 59

From what you have shown: Your css style selector should indeed be $("div > a") (citing dystroy) if only if the a-tag is an immediate descendant (i.e. child) of a div-tag otherwise I'd rather go for $("div a") which will search all descendants.

Note i've removed #div from here - I'm assuming you really mean a reference to a div-tag and not some element with the id 'div'. If the id is actually "div" then yeah use #div.

Upvotes: 0

plalx
plalx

Reputation: 43718

"what if I want to itterate through elements in a specific div, I tried using the ('#div' > a) selector but that doesn't seem to work"

It's $('#div > a'), and this will only target a elements that are direct children of the element with id div.

To iterate over these you can do the following:

$('#div > a').each(function (index) {
    console.log(this); //your a element
    console.log(index); //the loop index
});

Upvotes: 0

Related Questions