0

I want to iterate through a few HTML elements and get their values. I tried using $.each() for this but I can't figure out how to do it when an element has other elements of variable types inside it. I have the HTML DOM structure as :

<li>
 <div>X</div>
 <br/>
 <span>Category : </span>
 <div>Y</div>
 <span><br/>Rating</span>
 <div>
 <span>Z</span>
</div>

I want to retrieve the values X , Y , Z from it. Also there are multiple instances of this so I will have to iterate through each of them. Can anyone suggest some approach to this?

Aneesh
  • 1,691
  • 2
  • 22
  • 34

3 Answers3

1

Looks like you are reading the text content of all div elements within the li. So try

$('li').children('div').each(function(){
    console.log($(this).text())
})
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520
1

Assign the elements you are interested in to a class:

<li>
 <div class="value">X</div>
 <br/>
 <span>Category : </span>
 <div class="value">Y</div>
 <span><br/>Rating</span>
 <div>
 <span class="value">Z</span>
</div>

Then select values by class:

$('.values').each(function() {
  console.log($(this).text())
})
helpermethod
  • 55,449
  • 64
  • 175
  • 266
1

or

$('li > div').each(function(){
    console.log($(this).text())
})

-EDIT-

If you don't want any content inside those spans, you could try:

$('li > div').each(function(){
      var $tmp =  $(this).clone();
      $tmp.find('span').remove();
      console.log($tmp.text());

})
Toni Michel Caubet
  • 18,208
  • 50
  • 194
  • 356