How to update specific HTML element in a cell
How to update specific HTML element in a cell
Hi gang,
Looking for some guidance on how I can reference and update a specific HTML element in a cell of my DataTable. I can update the cell itself as a while with the cell().data() method, but I'm unsure how to target a specific element within. In this case, I want to update the <span> element with class "edit-name".
HTML Code:
The data-index value increments for each row in the DataTable.
<table id="myDataTable" class="assets-table">
<tbody>
<!-- Start Record -->
<tr data-index="0">
<td>
<!-- icon -->
<em class="fa-regular fa-file fa-xl ms-2"></em>
</td>
<td>
<!-- File -->
<div>
<a href="http://google.com" target="_blank">
<span class="edit-name">My Current File Name</span>
</a>
<!-- Tags -->
<span class="data-tags">
<span class="badge badge-dim bg-gray">HCLS</span>
</span>
</div>
<!-- Description -->
<span class="account-note">
This is an important file
</span>
</td>
<td>
<a href="javascript:;" class="edit-row" data-index="0">Edit</a>
</td>
</tr>
Javascript Code:
BTW, I had to use the .search('') method to overcome issues with updating cells while the datatable was filtered or searched. Key question here is...How do I update the SPAN element in the cell specifically?
$("#myDataTable tbody").on('click', '.edit-row', function() {
var myTable = $('#myDataTable').DataTable();
var unfilteredIndex = $(this).attr("data-index");
var cellColumn = 1;
var newFileName = "New File Name Update";
// This successfully updates the whole cell to the new value.
// BUT, how do I ONLY update the text in the SPAN element with class ID "edit-name"?
myTable.search('').cell(unfilteredIndex, cellColumn).data(newFileName).draw();
}
Thanks in advance everyone for the help!
This question has an accepted answers - jump to answer
Answers
You could use just a standard jQuery / JS search from the node (
cell().node()
) - e.g.:You would probably then want to call
cell().invalidate()
so DataTables will "see" the new data (for sorting / filtering).It does depend a little on if you are Ajax loading the data, and / or rendering it with
columns.render
though.Allan
Allan, thank you. That was excellent. Your suggestion worked perfectly.
Quick follow up question. I'm finding that if I use the cell.node().querySelector() method, the element can only have that one class name in it. If there are more than one classes, the querySelector seems to fail. Is that something folks have run into before?
Are you trying to query both classes? Or does it just fail if the element has two classes? I'd be surprised if that's the case, but happy to look at a test case if it's a simple one. It might be worth checking the docs to see if any clues there.
Colin