MartinDK81 MartinDK81 - 5 months ago 9
Javascript Question

Replace text of element that start with specific text

I have html like bottom code

<table>
<tr>
<td>
{name length='100'}
</td>
<td>
{otherText length='100'}
</td>
<td>
{otherText2 length='100'}
</td>
</tr>
</table>


I want to change
td
s text that start with
{name
.

How can i do this?

Answer

If you want to replace the whole inner text that starts with {name, try this:

function replace(newVal) {
    var tds = document.getElementsByTagName("td");
    for (var i = 0; i < tds.length; i++) {
        var elem = tds[i];
        if ( elem.innerText.startsWith("{name") ) {
            elem.innerText = newVal;
        }
    }
}

replace("new-value");
<body>
  <table>
    <tr>
      <td>
        {name length='100'}
      </td>
    </tr>
  </table>
</body>