MartinDK81
MartinDK81

Reputation: 343

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 tds text that start with {name.

How can i do this?

Upvotes: 1

Views: 162

Answers (3)

ROMANIA_engineer
ROMANIA_engineer

Reputation: 56616

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

// added this condition to have the startsWith function in all browsers
if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(searchString, position) {
        position = position || 0;
        return this.indexOf(searchString, position) === position;
    };
}

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>

Edit:

As Mohammad mentioned, the startsWith method is not supported in all browsers. See the table below:

╔═══════════════╦════════╦═════════╦═══════╦═══════════════════╦═══════╦════════╗
║    Feature    ║ Chrome ║ Firefox ║ Edge  ║ Internet Explorer ║ Opera ║ Safari ║
╠═══════════════╬════════╬═════════╬═══════╬═══════════════════╬═══════╬════════╣
║ Basic Support ║     41 ║      17 ║ (Yes) ║ No Support        ║    28 ║      9 ║
╚═══════════════╩════════╩═════════╩═══════╩═══════════════════╩═══════╩════════╝

This is why I added the condition above - to have the startsWith function in all browsers.

Upvotes: 1

Mohammad
Mohammad

Reputation: 21489

You can use jquery text(function) to iterating all tds text and use match() to checking text content by regex.

$("td").text(function(index, text){
    if (text.trim().match(/^{name/))
        return "Changed text";
});
table, tr, td {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      {name length='100'}
    </td>
    <td>
      {type length='100'}
    </td>
    <td>
      {other length='100'}
    </td>
  </tr>
</table>

Upvotes: 1

Luc Laverdure
Luc Laverdure

Reputation: 1470

$('td').html('{name '+new_text);

Upvotes: -1

Related Questions