I have the following table and I was trying to replace the string text of each 1st col with a link. So, the text “a1” and “a2” contents would be replaced with an according-to-link “google.com/a1” and “google.com/a2” etc…(whatever) .html contents.
Solution:
We can easily achieve this by using Jquery .each()
function, When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0.
<!DOCTYPE html>
<html lang="en">
<!-- How to replace first <td> column of a table?
How to replace text of a particular cell and make it hyperlink in a table -->
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table class="table table-striped table-bordered" cellspacing="0" cellpadding="3" rules="all" border="1"
id="Content1" >
<tbody>
<tr class="DashHeader" style="color:#545454;font-weight:bold;white-space:nowrap;">
<th scope="col" style="width:50px;">col1</th>
<th scope="col" style="width:50px;">Col2</th>
<th scope="col">Col3</th>
</tr>
<tr class="DashRow">
<td>a1</td>
<td>b1</td>
<td>c1</td>
</tr>
<tr class="DashAltRow">
<td>a2</td>
<td>b2</td>
<td>c2</td>
</tr>
<tr class="DashRow">
<td>a3</td>
<td>b3</td>
<td>c3</td>
</tr>
</tbody>
</table>
</body>
<script>
$('#Content1 td:first-child').each(function (i) {
var $td = $(this);
$td.html('<a href="google.com/ ' + $td.text() + '">' + "google.com/" + $td.text() + '</a>');
});
</script>
</html>
Concluson:
As we discussed in the solution Section, the .each()
method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this
refers to the element. We hope you find them helpful.