1

What I am trying to achieve:

The word online should appear green while the word offline should appear yellow. Everytime my webpage loaded.

What I have done: I have have searched for this on google all day and even on stackoverflow. All I could find is;

<head>
<style>
  .found {
    color:red;
  }
</style>
</head>
<body>
  <input id="s">
  <div id="a">
    i am online he is offline.
  </div>
  <script id="jsbin-javascript">
    var s = document.getElementById('s');
    var div = document.getElementById('a'); 

    function changeNode(n, r, f) {
      f=n.childNodes; for(c in f) changeNode(f[c], r);
      if (n.data) {
        f = document.createElement('span');
        f.innerHTML = n.data.replace(r, '<span class=found>$1</span>');
        n.parentNode.insertBefore(f, n);
        n.parentNode.removeChild(n);
      }
    }
    //s.onkeyup
    s.onkeyup = function(){
      var spans = document.getElementsByClassName('found');
      while (spans.length) {
        var p = spans[0].parentNode;
        p.innerHTML = p.textContent || p.innerText;
      }
      if (this.value) changeNode(
        div, new RegExp('('+this.value+')','gi')
      );
    };
  </script>
</body>

So whenever, I type something into the input box, the words become highlighted. However, I want this to happen automatically without ant input box and the word online in green and offline in yellow.

Thanks in advance.

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135

6 Answers6

2

You can use this approach:

<html>
 <head>
   <style>
     .green {
       color: green;
     }
     .red {
       color: red;
     }
  </style>
</head>
<body>
  <h1 id="colouredText">This is a green text, and here a red text</h1>
  <script>
    var text = document.getElementById("colouredText");
    var words = text.innerHTML.split(" ");
    for(var i = 0; i < words.length; i++) {
      if(words[i] == "red") {
        words[i] = "<span class='red'>" + words[i] + "</span>";
      }
      if(words[i] == "green") {
        words[i] = "<span class='green'>" + words[i] + "</span>";
      }
    }
    text.innerHTML = words.join(" ");
  </script>
</body>

2

Here is a vanilla javascript which:

  1. loops through the elements in the document to find the paragraphs;
  2. breaks up the paragraphs into space-separated words;
  3. replaces every instance of online and offline with a styled span; and
  4. reconstructs the paragraph including the styled spans

var body  = document.getElementsByTagName('body')[0];

for (var i = 0; i < body.childNodes.length; i++) {
    if (body.childNodes[i].nodeName !== 'P') {continue;}

    var textArray = body.childNodes[i].textContent.split(' ');
    body.childNodes[i].textContent = '';

    for (var j = 0; j < textArray.length; j++) {

        if (textArray[j] === 'online') {
            var online = document.createElement('span');
            var onlineText = document.createTextNode('online');
            online.appendChild(onlineText);
            online.classList.add('online');
            textArray[j] = online;
        }

        else if (textArray[j] === 'offline') {
            var offline = document.createElement('span');
            var offlineText = document.createTextNode('offline');
            offline.appendChild(offlineText);
            offline.classList.add('offline');
            textArray[j] = offline;
        }

        else {
            textArray[j] = document.createTextNode(textArray[j]);
        }

        body.childNodes[i].appendChild(textArray[j]);

        if (j < (textArray.length - 1)) {
            var space = document.createTextNode(' ');
            body.childNodes[i].appendChild(space);
        }
    }
}
.online {
color: rgb(0,255,0);
}

.offline {
color: rgb(255,255,0);
}
<p>upline downline inline outline underline overline online offline upline downline inline outline underline overline upline downline inline outline underline overline online offline upline downline inline outline underline overline upline downline inline outline underline overline online offline upline downline inline outline underline overline upline downline inline outline underline overline online offline upline downline inline outline underline overline</p>

<p>underline overline online offline upline downline inline outline underline overline online offline upline downline inline outline underline overline online offline upline downline inline outline underline overline online offline upline downline inline outline underline overline online offline upline downline inline outline underline overline online offline upline downline inline outline underline overline online offline upline downline inline outline</p>
Rounin
  • 27,134
  • 9
  • 83
  • 108
1

Actually, there is a very easy and new way to do this.

just add #:~:text=Highlight%20These

try accessing this link

https://stackoverflow.com/questions/38588721#:~:text=Highlight%20a%20text

Note: Only for chrome :(

Jovylle
  • 859
  • 7
  • 17
0

I don't see why you need Javascript to accomplish something like this. Well at least in the way that you explained.

Why couldn't you just do this with plain html like so:

<div id="a">
    i am <span style="color:green">online</span> he is <span style="color:yellow">offline</span>.
</div>

Here is a JSfiddle

Let me know if this helps.

Grizzly
  • 5,873
  • 8
  • 56
  • 109
0

Try using this after you include Jquery. or Just call the startHighlightProcess method when you like.

$(document).ready(function(){
startHighlightProcess("online","onlineClass");
startHighlightProcess("offline","offlineClass");
});

function startHighlightProcess(keywordToHighlight,classname)
var searchedKeyword = keywordToHighlight;
var newClassToSet = classname;
        function startHighlighting() {                
                    highlightWord(document.body, searchedKeyword.toLowerCase());
            };



            function highlightWord(root, word) {
var classToSet = newClassToSet;
                textNodesUnder(root).forEach(highlightWords);

                function textNodesUnder(root) {
                    var walk = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null, false),
                        text = [], node;
                    while (node = walk.nextNode()) text.push(node);
                    return text;
                }

                function highlightWords(n) {
                    for (var i; (i = n.nodeValue.toLowerCase().indexOf(word, i)) > -1; n = after) {
                        var after = n.splitText(i + word.length);
                        var highlighted = n.splitText(i);
                        var span = document.createElement('span');
                        span.className = classToSet;
                        span.appendChild(highlighted);
                        after.parentNode.insertBefore(span, after);
                    }
                }
            }
Rahul Malu
  • 556
  • 2
  • 9
0

JQuery - Targeting all paragraphs that satisfy the filter

var textToFind = 'online';

$("p:contains('" + textToFind + "')").each(function (i, element) {
    // extract the element content
    var content = $(element).text();

    // replace the text to find with the new mark up
    content = content.replace(textToFind, '<span class="highlight">' + textToFind + '</span>');

    // put back into the element
    element.html(content);
});

Be aware that this will replace the contents of the paragraph with the new content, if there are any handlers associated with elements in the paragraph they will be lost.

Use carefully.

ashto5
  • 19
  • 3