Reputation: 29427
I have the following markup
<div id="FirstDiv">
<div class="MyClass">
<span>
<a href="#">link 1</a>
<a href="#">link 2</a>
</span>
</div>
</div>
<div id="SecondDiv">
<div class="MyClass">
<span>
<a href="#">link 1</a>
<a href="#">link 2</a>
</span>
</div>
</div>
How can I select alla the <a>
tag elements inside the DIV "SecondDiv"?
Actually I am doing
$(".MyClass > a").click(function (event) {
but this would select also links of the first div.
Upvotes: 1
Views: 74
Reputation: 322452
$('#SecondDiv a')
This uses the ID of the SecondDiv
element, and selects all descendant <a>
elements.
You were using the >
child selector, which would only select immediate children. And you're right that it would select from both .MyClass
elements.
Another possibility would be to place a .delegate()
on the SecondDiv
element to match clicks against the nested <a>
elements.
$('#SecondDiv').delegate( 'a', 'click', function() {
// your code
});
EDIT: In reference to your comment below, you can limit it to <a>
elements in the .MyClass
element by placing that in the selector.
$('#SecondDiv .MyClass a')
Now any <a>
elements that do not descend from .MyClass
will not be included.
Upvotes: 4
Reputation: 12417
why dontb yu use id of second div ('#second div')
or
http://api.jquery.com/children/
Upvotes: 0
Reputation: 10071
You should use the ID Selector (#) over here instead of the class selector (.)
$("#SecondDiv a").click(function (event) {
Read more about ID Selector and Class selector.
Upvotes: 2