0

Assume I have a body such as;

<div class="body">
    <ul>
        <li class="01">hi</li>
        <li class="02">bye</li>
        <li class="03">go</li>
    </ul>

    <ul style="">
        <li class="01">hi2</li>
        <li class="02">bye2</li>
        <li class="03">go2</li>
    </ul>
</div>

I want to get each class = "01", class = "02" and class = "03" values of each ul.

What I did so far?

$('.body ul').each(function(element)
{
   console.log(this);
});

It printed the each li element but how can I reach the values in class 01,02 and 03?

I want to get

hi bye go hi2 bye2 go2

while looping inside the body

WOUNDEDStevenJones
  • 4,003
  • 5
  • 37
  • 46
user6468132
  • 253
  • 1
  • 4
  • 15
  • `$(this).find(".01").text()` to select for that class, or `$(this).children().each(function() { console.log($(this).text();); }`? – nnnnnn Aug 14 '16 at 07:15
  • 1
    Note that using number alone in class name is not a good idea (might work in some browsers, but might not work in others or in other cases). First character for class name should be letter. See: http://stackoverflow.com/questions/448981/which-characters-are-valid-in-css-class-names-selectors – Nux Aug 16 '16 at 09:56

2 Answers2

1

Have a look at Selector Documentation.

  1. $("li.02") - for all <li> with class 02
  2. $(".body>ul>li.02") - for all <li> with class 02 inside a <ul> inside an element with class body.

//for all <li> with class "02"
$('li.02').each(function(element) {
  console.log(this.innerHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body">

  <ul>
    <li class="01">hi</li>
    <li class="02">bye</li>
    <li class="03">go</li>
  </ul>

  <ul style="">
    <li class="01">hi2</li>
    <li class="02">bye2</li>
    <li class="03">go2</li>
  </ul>

</div>
Graham
  • 6,577
  • 17
  • 55
  • 76
Iceman
  • 5,455
  • 1
  • 20
  • 34
0

$('li.01').text(); returns the string in the element. If you want to output the strings for each class you can do:

$('li.01').each(function(element) {
  console.log($(this).text());
});

and for all list items

$('li').each(function(element) {
  console.log($(this).text());
});