Reputation: 4625
I have a nested div structure as follows:
<div id="outer">
<h3 id="groupa">group a</h3>
<div id="inner1">
<div id="inner2">
<h3 id="groupb">group b</h3>
<div id="inner3">
<div id="inner4">
</div>
and when a user clicks any of the inner divs (inner?) a click hander is supposed to pass the id of the group (the nearest h3 above it), and the id of the inner div itself. So, for example, clicking the last inner div would call a function with parameters "groupb" and "inner4".
I need to 1. Create the jQuery select which associates the click handler with only the inner? divs, and 2. make the handler call a function with these 2 parameters. Something like:
$('#outer div').click(function () {
myfunction(this.h3above.id,this.id);
});
Can someone help with the 3 lines of code above to select correctly, and get the 2 id's needed?
Upvotes: 1
Views: 4187
Reputation: 1613
You can use jQuery's prevAll()
function to select the previous h3
element:
$('#outer div').click(function () {
var h3_id = $(this).prevAll('h3').attr("id");
var id = $(this).attr("id");
myfunction(h3_id, id);
});
The prevAll
function gets "all the preceding sibling of each element in the set of matched elements, optionally filtered by a selector." (jQuery API)
Like the commenters above said, though, you should change the id
's of your inner divisions to classes, since ids are supposed to be unique for valid HTML.
Upvotes: 3
Reputation: 186
As the two commenters noted you should have unique id's.
I have a jsFiddlehere for you on how to fetch id's.
I added classes to the clickable elements and bound the click event on that. Assuming the h3 is on the same level as the 'inner' divs use the .prev function to find the h3 and fetch its id.
That all being said the best practice is to really group your inner elements better and use unique id's. Multiple elements can have the same class but not ids.
Slightly modified HTML:
<div id="outer">
<h3 id="groupa">group a</h3>
<div id="inner1" class="clickable">Click here</div>
<div id="inner2" class="clickable">Click here</div>
<h3 id="groupb">group b</h3>
<div id="inner3" class="clickable">Click here</div>
<div id="inner4" class="clickable">Click here</div>
</div>
<br/><br/>
Your Results:
<br/><br/>
<div class="output1"></div><!--This inner's closest h3-->
<div class="output2"></div> <!--This inner ID-->
Javascript:
$('.clickable').click(function(){
//.attr fetches the attribute value
$('.output1').text($(this).attr('id'));
$('.output2').text($(this).prev('h3').attr('id'));
/*
$(this).attr('id') -- this contains the clicked element id
$(this).prev('h3').attr('id') -- this contains the closest h3's id
you could store them in a variable and then call your function with it.
*/
});
Upvotes: 0
Reputation: 388446
$('#outer').on('click', 'div[id^=inner]', function(e){
var h3_id = $(this).prevAll('h3').attr("id");
var id = $(this).attr("id");
myfunction(h3_id, id);
})
demo: Fiddle
Upvotes: 0