Skip to content
Advertisement

Replace old value with new value excluding the children

The initial text of A, B, C, D, and the number need to be removed in the frontend because I require it in the backend.

The HTML structure of table row is like this:

<tr ng-repeat="(key, field) in nbd_fields" ng-show="field.enable &amp;&amp; field.published" class="ng-scope">
  <td class="ng-binding">A,B,C,D: 1 - Auswahl Wunschkarte : <b class="ng-binding">Wähle eine Option</b>
  </td>
  <td ng-bind-html="field.price | to_trusted" class="ng-binding"></td>
</tr>

Before Input:

Before input

Current Output:

Current output

If you notice that the selected option is also not visible. Is it because of the $(window).load() ?

Required Output:

Required output

Code that I am using:

jQuery(".ng-scope td.ng-binding:first-child").text(function(i, oldVal) {
    return oldVal.replace(/^[^-]+ - /,""); 
 });
});

How can I make it so that it does not affect the <b> tag inside?

I used the above code for the steps heading with a different selector on the same page* and it worked because it did not have any children to alter.

I had to wrap it around $(window).load() so that the changes are applied after the table is loaded. $(document).ready() did not work with it. Not sure why?

Advertisement

Answer

(Edit: Modified to accommodate restated requirement in comment below.)

To strip “everything up to and including the ‘-‘” from the text of first column table cells while leaving the rest untouched:

// strip "everything up to and including the '-'"
// from table cell contents
function stripPrefix(tblCell) {
 // only evaluate first td in tr
  if (tblCell.previousElementSibling) {
    return;
  }
  const tNode = tblCell.firstChild;
  // ignore if table cell is empty
  if (!tNode) {
    return;
  }
  const chars = tNode.nodeValue.split('');
  const iFirstDash = chars.indexOf('-');
  if (iFirstDash === -1) { return; }
  tNode.nodeValue = chars.slice(iFirstDash+1).join('');
}

function stripAllPrefixes() {
  const tds = document.getElementsByTagName('td');
  for (const td of tds) {
    stripPrefix(td);
  }
}
td {
  border: 1px solid gray;
}
<h4>Strip "everything up to and including the '-'" from Table Cells</h4>
<table>
  <tr>
    <td>A,B,C,D: 1 - Auswahl Wunschkarte : <b>Wähle eine Option</b></td>
    <td></td>
  </tr>
  <tr>
    <td>B,C,D,E: 20 - A different leader : <b>should also be stripped</b></td>
    <td></td>
  </tr>
  <tr>
    <td>Oops no dash here <b>Just checking</b></td>
    <td></td>
  </tr>

</table>

<button onclick="stripAllPrefixes();">Strip All</button>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement