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!
4 Answers 4
how about
function getNodeDisplay(node) {
return $(node).find(".display").html();
}
the find function searches the dom tree under th current element.
Comments
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();
}
Comments
Try this:
$(node).find(".display").html()
Comments
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
});