1

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.

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

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.

Comments

2
$("#SecondDiv a").click(function(){
  alert("Hi-o");
});

Comments

1
$("#SecondDiv").find("a").click(function(event) {});

Comments

0

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

or

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.