Reputation: 343
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?
Upvotes: 1
Views: 162
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
Reputation: 21489
You can use jquery text(function)
to iterating all td
s 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