codenoob codenoob - 1 month ago 10
Javascript Question

jquery select by class then match value

I have a list like this

<ul>
<li class="somename">1</li>
<li class="somename">2</li>
<li class="somename">3</li>
<li class="somename">1</li>
</ul>


then I have a value like this

var myvalue = 1;


I want to compare myvalue with all the
$(".somename).text()
to find the matching ones and change the text of the matching to something else like below

<ul>
<li class="somename">changed</li>
<li class="somename">2</li>
<li class="somename">3</li>
<li class="somename">changed</li>
</ul>


$(".somename").text()
give me all the text in a string like 1231

and I tried to for loop

for(i=0;i<$(".somename").length;i++){
if(myvalue == $(".somename")[i].text()){
$(this).text("changed")
}
}

Answer

$('.somename').each(function() {

  var value = $(this).text();

  if (value == "1") {
    $(this).text("Changed")

  }

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="somename">1</li>
  <li class="somename">2</li>
  <li class="somename">3</li>
  <li class="somename">1</li>
</ul>

  1. Use .each() to loop through all elements with the class.
  2. Have a condition , if met change the text