user336206 user336206 - 7 months ago 12
Javascript Question

Getting data out of Divs

I have the following structure:

<div id="main">
<div id="myDiv1">
<ul>
<li>Abc</li>
<li>Def</li>
</ul>
</div>
<div id="myDiv2">
<ul>
<li>Ghi</li>
<li>Jkl</li>
</ul>
</div>
</div>


There can be several
myDivX
.

I want to get some information out of it in the following way:

myDiv1
Abc
Def
myDiv2
Ghi
Jkl


This is my approach:

$("#main").each(function() {
$("div").each(function() {
console.log(this.id)
});
$("ul").each(function() {
console.log(this)
});
});


It gives me this:

main
myDiv1
myDiv2
<ul>​<li>​Abc​</li>​<li>​Def​</li>​</ul>​
<ul>​<li>​Ghi​</li>​<li>​Jkl​</li>​</ul>​


Fiddle.

Answer

You can do it like this DEMO

$('#main div').each(function() {
  console.log($(this).attr('id'));
  $(this).find('li').each(function() {
    console.log($(this).text());
  });
});