views:

36

answers:

5

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.

+4  A: 
$('#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.

patrick dw
Is there a way to use also the Myclass selector like `$('#SecondDiv .MyClass a')`
Lorenzo
@Lorenzo - Yes, if there will be other `<a>` elements under `SecondDiv` that are not also under `.MyClass`, then that selector would eliminate those.
patrick dw
+2  A: 

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.

ShiVik
+2  A: 
$("#SecondDiv a").click(function(){
  alert("Hi-o");
});
John
+1  A: 
$("#SecondDiv").find("a").click(function(event) {});
Krishna Chytanya
A: 

why dontb yu use id of second div ('#second div')

or

http://api.jquery.com/children/

zod