luka032 luka032 - 3 months ago 6
HTML Question

How to get multiple labels' values via class name?

How could I get all values of labels that contains class "timeAuction"?

I am writing JavaScript function that will get each label with class name

timeAuction
and modify its value. I've got random number of labels with this class name.

Here's my code that renders html:

<label id="@Html.Raw("time" + item.IDAuc)" class="displayLabelProduct timeAuction">
@diff.ToString(@"dd\:hh\:mm\:ss")
</label>


I would need to go through each label with this class, something like for loop and modify it.

Answer

You can select all elements using the class selector:

var allElements = $(".timeAuction");

You can also use $.each to iterate the collection.

$(".timeAuction").each(function() {
   $(this).text("Random value");
});

Full snippet showing modification of labels:

$(".timeAuction").each(function(counter) {
   $(this).text("New Label " + counter);
});
label {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<label class="displayLabelProduct timeAuction">
    Label 1
</label>

<label class="displayLabelProduct timeAuction">
    Label 2
</label>

<label class="displayLabelProduct timeAuction">
    Label 3
</label>

<label class="displayLabelProduct timeAuction">
    Label 4
</label>