March 31, 2012
getting the child text from a div in a .each loop
Question by randy
this is just a couple of lines of code that i have in my page.
I am using the jquery ui drag and drop. These are two of the items of many
when the saved button is press i need to get all the IDs and the text in the group_name div
This function gets the ID ok but i can not figure out how to get the $(‘group_name’).text() from the current LI in the each loop.
function saveChanges(){
$("li.ui-state-default").each(function() {
var $divitem = $( this );
console.log($divitem.attr('id'));
});
}
this is the html snippet
<li id="5" class="ui-state-default">
<div class="group_name">Classes</div>
<div class="group_footer">
<a title="Delete this group" class="mytrash-icon" href="#">
<img border="0" src="trash.png" class="mytrash-img"></a>
<a title="Manage Subfolders" class="subfolder" href="#">
<img border="0" src="Folder-Icon.png"></a>
</div>
</li>
<li id="6" class="ui-state-default">
<div class="group_name">Coaching</div>
<div class="group_footer">
<a title="Delete this group" class="mytrash-icon" href="#">
<img border="0" src="trash.png" class="mytrash-img"></a>
<a title="Manage Subfolders" class="subfolder" href="#">
<img border="0" src="Folder-Icon.png"></a>
</div>
</li>
Thanks for any help!
Answer by Starx
One way would be to use .find()
$("li.ui-state-default").each(function() {
var $divitem = $(this);
console.log($divitem.find(".group_name").text());
});
Another would be to use .children()
$("li.ui-state-default").each(function() {
var $divitem = $(this);
console.log($divitem.children(".group_name").text());
});
But the one I like is neither
$("li.ui-state-default").each(function() {
var $divitem = $(this);
console.log($(".group_name", $divitem).text());
});