Change color to a word

1

I have a table made with HTML and JavaScript .

var ths = document.getElementsByTagName("th");
var tds = document.getElementsByTagName("td");

for (var i = 0; i < ths.length; i++) {

  ths[i].style.color = "red";

}

for (var i = 0; i < tds.length; i++) {

  tds[i].style.color = "green";

}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
 
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
 
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>80</td>
  </tr>
</table>

</body>
</html>

And I would like that through Basic JavaScript (I'm learning to use it and not beyond Jquery), locate me and modify the color of a word, which in this case would be John . I know it can be through this function:

color = document.getElementsByTagName('td');
color[6].style.color="green";

But it does not do the function of looking for the word, finding the word and changing it the color of the word.

    
asked by Reinos Ric 25.07.2017 в 20:35
source

1 answer

2

You can use advanced JS features. You must use document.designMode together with execCommand to be able to edit the document.

Most of the commands affect the document selection (bold, italic, etc.), while others insert new elements (adding a link) or affect an entire line (indentation).

I show you how your code would look:

    //recuperamos el valor que queremos resaltar
    var text = "John";
    document.designMode = "on";
    var sel = window.getSelection();
    sel.collapse(document.getElementById("resultat"), 0);

    while (window.find(text)) {
        document.execCommand("HiliteColor", false, "lightgreen");
        sel.collapseToEnd();
    }
    document.designMode = "off";
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
</head>

<body>
    <table style="width:100%">
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Age</th>
        </tr>
        <tr>
            <td>Jill</td>
            <td>Smith</td>
            <td>50</td>
        </tr>

        <tr>
            <td>Eve</td>
            <td>Jackson</td>
            <td>94</td>
        </tr>

        <tr>
            <td>John</td>
            <td>Doe</td>
            <td>80</td>
        </tr>
    </table>

</body>


</html>

answered by 25.07.2017 / 22:59
source