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>
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 bee 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.
Share edited Jul 26, 2016 at 12:32 Mosh Feu 29.4k18 gold badges93 silver badges141 bronze badges asked Jul 26, 2016 at 11:30 Tim Berners LeeTim Berners Lee 311 silver badge3 bronze badges 5- Why don't you just wrap them in spans in the HTML? – gcampbell Commented Jul 26, 2016 at 11:32
- You can use the javascript onload event <body onload="myFunction()"> – Ram Segev Commented Jul 26, 2016 at 11:35
- In all honesty the solution you currently have is not desirable for what you want to do. As @gcampbell remends splitting them up as elements would be better and styling them would be best. – N.J.Dawson Commented Jul 26, 2016 at 11:36
- This might help - stackoverflow./questions/8644428/… – this.shivi Commented Jul 26, 2016 at 12:08
- Try my new answer – Jovylle Commented Jun 24, 2020 at 14:51
6 Answers
Reset to default 3You 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>
</html>
Here is a vanilla javascript which:
- loops through the elements in the document to find the paragraphs;
- breaks up the paragraphs into space-separated words;
- replaces every instance of online and offline with a styled
span
; and - 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>
Actually, there is a very easy and new way to do this.
just add #:~:text=Highlight%20These
try accessing this link
https://stackoverflow./questions/38588721#:~:text=Highlight%20a%20text
Note: Only for chrome :(
I don't see why you need Javascript to acplish 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.
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);
}
}
}
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.