Home > OS >  Remove Last Character in th using ajax
Remove Last Character in th using ajax

Time:03-21

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?

CodePudding user response:

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

CodePudding user response:

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>

  • Related