Ryan Palmer
Ryan Palmer

Reputation: 543

How to get the ID of a nested div to build a var with

I'm trying to build a var to be used in a function. The function needs to run on multiple div's that have separate ID's. Essentially, the var would be grabbing the ID of each div and running the function based on that. I just can't get it working correctly.

Here's my markup:

<div class="group">
    <div id="element1" class="element">Stuff</div>
    <div id="element2" class="element">Stuff</div>
</div>

Here's my jQuery var "attempt" :)

var elementVar = $('.group').find('.element')this.attr('id');

So essentially, will be ran like the following, so that the function runs on each div id

$(elementVar).click(function(){ ...

Any help would be hugely appreciated!

Upvotes: 1

Views: 4682

Answers (4)

Purag
Purag

Reputation: 17061

Just use this:

$(".group").children().each(function(){});

This gets all the children of the div with class group and applies the function within the each() jQuery function to them.

So to trigger a function on click:

$(".group").children().each(function(){
  $(this).click(function(){
    // click event here
  });
});

Also, as long as all the divs will have classes, just select the class:

$(".element").each(function(){
  $(this).click(function(){
    // click event here
  });
});

But you probably only added classes so your method would work. If you're not going to add classes, then the first method is your best option.

More on children(); here and more on each(); here.

Upvotes: 0

Ariful Islam
Ariful Islam

Reputation: 7675

Isn't it just simple

$('.element').click(function(){
   id = $(this).attr('id');
});

Upvotes: 1

Moe Sweet
Moe Sweet

Reputation: 3721

$('.group .element').click(function(){
id = $(this).attr('id');
});

but i recommend something like this. It gives you the clean data.

<div id="element2" class="element" data-id="2">Stuff</div>
$('.group .element').click(function(){
id = $(this).attr('data-id');
});

Upvotes: 5

Marc B
Marc B

Reputation: 360682

This should do the trick:

$('.group div.element').click(function() {
   $(this).....;
});

Upvotes: 2

Related Questions