user6468132 user6468132 - 3 months ago 7
HTML Question

Get each li value with a specific class name

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

Answer

Have a look at Selector Documentation at SO 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>

Comments