I have the following table & what is the best way to make the cell of table <td>
clickable/hyperlink based on the text it has.
<table id="fresh-table" class="table">
<thead>
<th data-field="id" data-sortable="true">ID</th>
<th data-field="URL" data-sortable="true">URL</th>
<th data-field="Results">Results</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td><a href="#">https://google.com</td>
<td>Woot</td>
</tr>
<tr>
<td>1</td>
<td><a href="#">https://facebook.com</td>
<td>Hax</td>
</tr>
</tbody>
</table>
$(document).ready(function(){
var x = $('.clickme').getText();
console.log(x);
});
I would like to replace the values of href
based on text it got ex: https://google.com
or https://facebook.com
.
Firstly, note that your HTML is invalid; you're missing the </a>
tags to close the anchors within the table
.
Secondly, jQuery has no getText()
method. I would assume you meant to use text()
instead.
With regard to your question, you can use prop()
to set the href
attribute of the a
elements equal to their text()
. The simplest way to do this is to provide a function to prop()
which will be executed on each element in the collection. Try this:
$('#fresh-table a').prop('href', function() { return $(this).text(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="fresh-table" class="table"> <thead> <th data-field="id" data-sortable="true">ID</th> <th data-field="URL" data-sortable="true">URL</th> <th data-field="Results">Results</th> </thead> <tbody> <tr> <td>1</td> <td><a href="#">https://google.com</a></td> <td>Woot</td> </tr> <tr> <td>1</td> <td><a href="#">https://facebook.com</a></td> <td>Hax</td> </tr> </tbody> </table>
you can achieve that without jQuery
in just few lines of code:
document.addEventListener("DOMContentLoaded", () => {
for (const element of document.querySelectorAll("a[href='#']")) {
element.href = element.innerText;
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.