Reputation: 11
I have a table displays opening hours for various locations and looks somewhat like the following structure;
<table class="tblServices">
<tbody>
<tr class="name loc1">
<td class="name">loc1</td>
<td class=""tcDayTimes">9-5</td>
<td class="tcDayTimes">9-5</td>
</tr>
<tr class="name loc2">
<td class="name">loc1</td>
<td class="tcDayTimes">9-5</td>
<td class="tcDayTimes">9-5</td>
</tr>
</tbody>
</table>
What I would like to be able to do is change the value of all table cells with the class "tcDayTimes" within the row the class "loc2", I have gotten close with the following jquery but its replacing the values for every cell with that class no matter what table row its in.
<script type="text/javascript">
$('.tblServices > tbody > tr.loc2').each(
$('td.tcDayTimes').html("24 hours")
Can some provide some advice as to where I am going wrong?
Thanks in advance
Upvotes: 0
Views: 1850
Reputation: 3512
You were close. In your selector, you need to add > .tcDayTimes
, which stores the items into a NodeList. Then use .html()
to change the html of all those elements.
$(".tblServices > tbody > .loc2 > .tcDayTimes").html("24 hours");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tblServices">
<tbody>
<tr class="name loc1">
<td class="name">loc1</td>
<td class="tcDayTimes">9-5</td>
<td class="tcDayTimes">9-5</td>
</tr>
<tr class="name loc2">
<td class="name ">loc1</td>
<td class="tcDayTimes">9-5</td>
<td class="tcDayTimes">9-5</td>
</tr>
</tbody>
</table>
You can also use the following method to do this in vanilla javascript. This basically uses .querySelectorAll()
to select the values you wanted and store them into a NodeList (like an array). Then you can use .innerHTML
to set the html of those elements.
var elements = document.querySelectorAll(".tblServices > tbody > .loc2 > .tcDayTimes");
elements.forEach(e => {
e.innerHTML = "24 hours";
});
<table class="tblServices">
<tbody>
<tr class="name loc1">
<td class="name">loc1</td>
<td class="tcDayTimes">9-5</td>
<td class="tcDayTimes">9-5</td>
</tr>
<tr class="name loc2">
<td class="name ">loc1</td>
<td class="tcDayTimes">9-5</td>
<td class="tcDayTimes">9-5</td>
</tr>
</tbody>
</table>
You dont need the >
. You can just have .tblServices tbody .loc2 .tcDayTimes
, but it makes it look neater, and I would keep it there if I were you.
Upvotes: 0
Reputation: 24965
You have a typo in your html, but otherwise...
$('.tblServices > tbody > tr.loc2').each(function(){
$('td.tcDayTimes', this).html("24 hours")
});
Where this
is the tr you are iterating over. The second argument to the $()
is the context.
OR
$('.tblServices > tbody > tr.loc2 td.tcDayTimes').html("24 hours");
Upvotes: 2