'Remove Last Character in th using ajax

How to remove last character inside of table header using javascript/ajax?

Example table:

Product Price X
First 1000
Second 2000

What I want to reach is remove the X on Price X column header with some button, I've use slice before but not working.

How I supposed to do?



Solution 1:[1]

try this function:

function noLastCharaceter(txt) {
  return txt.substr(0, txt.length - 1);
}

If you are asking, how to use it, so if your table id is "tableId", try this:

var table = document.getElementById("tableId"); 
var headers = table.getElementsByTagName("TH"); // list of "th" elements
headers[1].innerHTML = noLastCharacter(headers[1].innerHTML); // replace content of second column

Solution 2:[2]

Here is a very similar script that demonstrates the use of a suitable selector and a simple .slice() operation on the .textContent of the <th> element (please note that String.prototype.substr() is deprecated).

const th=document.querySelector("#myTable th:last-child");
th.textContent=th.textContent.slice(0,-2)
<table id="myTable"><thead><tr><th>Product</th><th>Price X</th><tr></thead><tbody>
<tr><td>First</td><td>1000</td></tr>
<tr><td>Second</td><td>2000</td></tr>
</tbody></table>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michal Politzer
Solution 2 Carsten Massmann