I have a HTML Table:
JavaScript
x
15
15
1
<table id="colorTable">
2
<tr>
3
<th>Name</th>
4
<th>Favorite Color</th>
5
</tr>
6
<tr>
7
<td>Tom</td>
8
<td>Orange</td>
9
</tr>
10
<tr>
11
<td>Sam</td>
12
<td>Red</td>
13
</tr>
14
</table>
15
I want to make a JS function that will find "Sam"
in the first column and replace the second column with "Green"
JavaScript
1
4
1
function replace(search, replace) {
2
3
}
4
This is a function based off another article, it find any word matching searchText
in the table and replaces it with the replace
string. What I want to do is filter only by the first column and then change the text in the second column of the found row.
JavaScript
1
35
35
1
function findAndReplace(searchText, replacement, searchNode) {
2
if (!searchText || typeof replacement === 'undefined') {
3
// Throw error here if you want...
4
return;
5
}
6
var regex = typeof searchText === 'string' ?
7
new RegExp(searchText, 'g') : searchText,
8
childNodes = (searchNode || document.body).childNodes,
9
cnLength = childNodes.length,
10
excludes = 'html,head,style,title,link,meta,script,object,iframe';
11
while (cnLength--) {
12
var currentNode = childNodes[cnLength];
13
if (currentNode.nodeType === 1 &&
14
(excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
15
arguments.callee(searchText, replacement, currentNode);
16
}
17
if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) {
18
continue;
19
}
20
var parent = currentNode.parentNode,
21
frag = (function(){
22
var html = currentNode.data.replace(regex, replacement),
23
wrap = document.createElement('div'),
24
frag = document.createDocumentFragment();
25
wrap.innerHTML = html;
26
while (wrap.firstChild) {
27
frag.appendChild(wrap.firstChild);
28
}
29
return frag;
30
})();
31
parent.insertBefore(frag, currentNode);
32
parent.removeChild(currentNode);
33
}
34
}
35
Advertisement
Answer
Analyse that:
JavaScript
1
9
1
function changeColor(name, color) {
2
$("#colorTable tr").each(function(i, el){
3
if($(this).children("td:eq(0)").text() == name) {
4
$("#colorTable tr:eq("+i+")").children("td:eq(1)").text(color);
5
}
6
});
7
}
8
9
changeColor("Sam", "Green");
JavaScript
1
26
26
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<meta charset="utf-8">
5
<meta name="viewport" content="width=device-width">
6
<title>JS Bin</title>
7
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
8
</head>
9
<body>
10
<table id="colorTable">
11
<tr>
12
<th>Name</th>
13
<th>Favorite Color</th>
14
</tr>
15
<tr>
16
<td>Tom</td>
17
<td>Orange</td>
18
</tr>
19
<tr>
20
<td>Sam</td>
21
<td>Red</td>
22
</tr>
23
</table>
24
25
</body>
26
</html>