1

I'm relatively new to JQuery. I'm trying to understand how to select a child element. Currently, I have some HTML that is defined as follows:

<div id="elem1">
 <div class="display">Student 1</div>
</div>
<div id="elem2">
 <div class="display">Student 2</div>
</div>
<div id="elem3">
 <div class="display">Student 3</div>
</div>

When a user clicks a link, one of the elements (elem1, elem2, or elem3) is going to be passed to a function that is defined as follows:

function getNodeDisplay(node) {
 // NOTE: This does not work as desired
 return $(node).(#".display").html();
}

Unfortunately, this approach does not work. How do I get the HTML associated with an element that has a specific class or a given element? Thank you for your help!

asked May 7, 2010 at 13:04

4 Answers 4

5

how about

function getNodeDisplay(node) {
 return $(node).find(".display").html();
}

the find function searches the dom tree under th current element.

answered May 7, 2010 at 13:06
Sign up to request clarification or add additional context in comments.

Comments

1

You can attach the click event when the page is loaded, and pass the jQuery object straight to your method:

$(document).ready(function() {
 $("div#elem*").each(function() {
 $(this).click(function() {
 getNodeDisplay($this);
 };
 };
});

div#elem* will match all div elements with the ID (#) beginning with elem.

To get the html:

function getNodeDisplay(node)
{
 return node.html();
}
answered May 7, 2010 at 13:07

Comments

0

Try this:

$(node).find(".display").html()
answered May 7, 2010 at 13:06

Comments

0

You can do it like this:

$("#elem1").click(function() {
 $(this).children(".display") //this is the child
});

.children() gets immediate children, the alternative .find() finds any descendant. If you want to assign this click handler to all of those elements, just give them a class as well like this:

<div id="elem1" class="clickMe">

And change your selector to use it, like this:

$(".clickMe").click(function() {
 $(this).children(".display") //this is the child
});
answered May 7, 2010 at 13:06

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.