Highlight a word with jQuery
Try highlight: JavaScript text highlighting jQuery plugin.
Warning: The source code available on this page contains a cryptocurrency mining script, either use the code below or remove the mining script from the script downloaded from the website.
/*
highlight v4
Highlights arbitrary terms.
<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
MIT license.
Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>
*/
jQuery.fn.highlight = function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(pat);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
}
else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.length && pat && pat.length ? this.each(function() {
innerHighlight(this, pat.toUpperCase());
}) : this;
};
jQuery.fn.removeHighlight = function() {
return this.find("span.highlight").each(function() {
this.parentNode.firstChild.nodeName;
with (this.parentNode) {
replaceChild(this.firstChild, this);
normalize();
}
}).end();
};
Also try the "updated" version of the original script.
/*
* jQuery Highlight plugin
*
* Based on highlight v3 by Johann Burkard
* http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
*
* Code a little bit refactored and cleaned (in my humble opinion).
* Most important changes:
* - has an option to highlight only entire words (wordsOnly - false by default),
* - has an option to be case sensitive (caseSensitive - false by default)
* - highlight element tag and class names can be specified in options
*
* Usage:
* // wrap every occurrance of text 'lorem' in content
* // with <span class='highlight'> (default options)
* $('#content').highlight('lorem');
*
* // search for and highlight more terms at once
* // so you can save some time on traversing DOM
* $('#content').highlight(['lorem', 'ipsum']);
* $('#content').highlight('lorem ipsum');
*
* // search only for entire word 'lorem'
* $('#content').highlight('lorem', { wordsOnly: true });
*
* // don't ignore case during search of term 'lorem'
* $('#content').highlight('lorem', { caseSensitive: true });
*
* // wrap every occurrance of term 'ipsum' in content
* // with <em class='important'>
* $('#content').highlight('ipsum', { element: 'em', className: 'important' });
*
* // remove default highlight
* $('#content').unhighlight();
*
* // remove custom highlight
* $('#content').unhighlight({ element: 'em', className: 'important' });
*
*
* Copyright (c) 2009 Bartek Szopka
*
* Licensed under MIT license.
*
*/
jQuery.extend({
highlight: function (node, re, nodeName, className) {
if (node.nodeType === 3) {
var match = node.data.match(re);
if (match) {
var highlight = document.createElement(nodeName || 'span');
highlight.className = className || 'highlight';
var wordNode = node.splitText(match.index);
wordNode.splitText(match[0].length);
var wordClone = wordNode.cloneNode(true);
highlight.appendChild(wordClone);
wordNode.parentNode.replaceChild(highlight, wordNode);
return 1; //skip added node in parent
}
} else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
!/(script|style)/i.test(node.tagName) && // ignore script and style nodes
!(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
for (var i = 0; i < node.childNodes.length; i++) {
i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
}
}
return 0;
}
});
jQuery.fn.unhighlight = function (options) {
var settings = { className: 'highlight', element: 'span' };
jQuery.extend(settings, options);
return this.find(settings.element + "." + settings.className).each(function () {
var parent = this.parentNode;
parent.replaceChild(this.firstChild, this);
parent.normalize();
}).end();
};
jQuery.fn.highlight = function (words, options) {
var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };
jQuery.extend(settings, options);
if (words.constructor === String) {
words = [words];
}
words = jQuery.grep(words, function(word, i){
return word != '';
});
words = jQuery.map(words, function(word, i) {
return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
});
if (words.length == 0) { return this; };
var flag = settings.caseSensitive ? "" : "i";
var pattern = "(" + words.join("|") + ")";
if (settings.wordsOnly) {
pattern = "\\b" + pattern + "\\b";
}
var re = new RegExp(pattern, flag);
return this.each(function () {
jQuery.highlight(this, re, settings.element, settings.className);
});
};
How to highlight all occurrences of a word on a page with Javascript or jQuery?
The best way is probably to use a .highlight
class to highlight the words and just wrap the matches in a span with that highlight class. Here is a basic example:
var sentences = document.querySelector('#sentences');var keywords = document.querySelector('#keywords');
keywords.addEventListener('click', function(event){ var target = event.target; var text = sentences.textContent; var regex = new RegExp('('+target.textContent+')', 'ig'); text = text.replace(regex, '<span class="highlight">$1</span>'); sentences.innerHTML = text;}, false);
.highlight { background-color: yellow;}
<div id="keywords"> <span>This</span> <span>Example</span>.</div><div id="sentences"> This is an example. An example is shown in this. Here is another example.</div>
Search and Highlight in jQuery
http://jsfiddle.net/UPs3V/291/
var src_str = $("#test").text();
var term = "my text";
term = term.replace(/(\s+)/,"(<[^>]+>)*$1(<[^>]+>)*");
var pattern = new RegExp("("+term+")", "gi");
src_str = src_str.replace(pattern, "<mark>$1</mark>");
src_str = src_str.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/,"$1</mark>$2<mark>$4");
$("#test").html(src_str);
try this one it may help you
How to search page for words and highlight them (JQuery)
It need to be done that way:
$(this).parent().html($(this).parent().html().replace($(this).text(),$(this).text().replace(regex, " <span style = 'background-color: " + searchList[i].color + " ;'>" + searchList[i].word + "</span> ")));
This is because when you change the innerHTML
directly you will mess the dom structure and lose the html format, when you change the text solely you would have a a sanitized DOM inside quotes, so it should be solved one way by modifying the text part inside the inner html.
see it here
How to highlight words in html using jquery
1. jQuery plugin to do highlighting:
/**
* jQuery plugin to replace text strings
*
* Taken from @link http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/
*/
$.fn.replaceText = function( search, replace, text_only ) {
return this.each(function(){
var node = this.firstChild,
val, new_val, remove = [];
if ( node ) {
do {
if ( node.nodeType === 3 ) {
val = node.nodeValue;
new_val = val.replace( search, replace );
if ( new_val !== val ) {
if ( !text_only && /</.test( new_val ) ) {
$(node).before( new_val );
remove.push( node );
} else {
node.nodeValue = new_val;
}
}
}
} while ( node = node.nextSibling );
}
remove.length && $(remove).remove();
});
};
2. CSS to style a span
element with a single highlight
class
span.highlight{
font-weight: bold;
text-decoration: underline;
}
3. jQuery code to run after you have included the plugin & style:
// replace partial string occurrences with a span css styled element
// i.e. textsample => text<span class="highlight">sample</span>
$('p').replaceText(/(sample)/gi, '<span class="highlight">$1</span>');
OR as suggested by @Nick C. in the comments
// replace full string occurrences with a span css styled element
// i.e. ONLY sample => <span class="highlight">sample</span>
$('p').replaceText(/\b(sample)\b/gi, '<span class="highlight">$1</span>');
Here is a demo
The plugin is smart enough not to replace the element's attributes, or text inside elements such as a
element...
Using jQuery, how can I highlight all new and existing occurrences of a word as the user types?
You should use /test/g
instead of .replace()
Here is a sample which works for your case:
$("#txt").keyup(function() { var txt = $(this).val(); var keyword = "test"; if (txt.indexOf(keyword) > -1){ $("#page").html(txt.replace(/test/g,'<span class="highlight">' + keyword + '</span>')); } else { $("#page").html(txt); }});
body { margin:0; padding: 0; font-family: Inter, sans-serif !important;}textarea { padding: 12x; font-family: Inter, sans-serif; font-size: 2em; height: 1.4em;}.highlight { color:red !important;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><textarea name="" id="txt" cols="30" rows="10"></textarea><div id="page"></div>
How to highlight in yellow a specific part of a string using jquery
You can replace a specific part of the string and wrap it. For better handling you should use a class and css for highlighting some parts.
var text = $('#myspan').text();text = text.replace('+', '<span style="color: yellow;">+</span>');$('#myspan').html(text)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><span id="myspan">Lorem ipsum dolor sit amet, consectetur adipiscing elit +</span>
live highlight a word(s) with jQuery
The issue is that after the first successful replace the pattern now has to also match the ending span tag that has been inserted after the first matched character.
The HTML looks like this after entering "l":
<p><span class="highlight">l</span>orem ip sum</p>
"lorem" will no longer match because of the span.
Now with solution:
Here is a fix that should get it doing what you want:
$('#' + id).each(function() {
$('span.highlight',this).replaceWith($('span.highlight',this).text()); // Fix
var content = $(this).html();
if (!content) return;
$(this).html(content.replace(pattern, o.template));
});
Assuming that you will only have a single highlight span, the line below removes the span and replaces it with the text that it contained. Then the replace happens as normal.
$('span.highlight',this).replaceWith($('span.highlight',this).text()
A working example is here: http://jsfiddle.net/ryanrolds/N4DCR/
Highlighting a word or sentence in iframe, using javascript/Jquery
As noted, CORS will not allow you to alter iFrames sourced from other domains you do not control without the proper CORS heading.
If you are on the same domain, you can possibly do something like find the word, alter it, and then replace the contents of the iframe with your new code. Here is a working fiddle and code For example:
<iframe src="http://fiddle.jshell.net/_display/" id="myIframe"></iframe>
<script>
var searchWord = "error";
$(document).ready(function(){
$('#myIframe').ready(function(){
var $html = $($('#myIframe').contents().find('body').html());
if($html.contents().text().search(searchWord)!=-1){
console.log("Found");
var replaceWith = "<span style='color:red'>"+searchWord+"</span>"
var newHTML = $html.text().replace(searchWord, replaceWith);
$('#myIframe').contents().find('body').html(newHTML);
}
});
});
</script>
Related Topics
When Is a Cdata Section Necessary Within a Script Tag
How to Move an Element into Another Element
Jquery/JavaScript Collision Detection
How to Disable HTML Button Using JavaScript
How to Store Arbitrary Data For Some HTML Tags
How Might I Get the Script Filename from Within That Script
Prevent Page Load on Jquery Form Submit With None Display Button
How to Draw an Inline Svg (In Dom) to a Canvas
Jquery Mobile: Markup Enhancement of Dynamically Added Content
How to Programmatically Set the Value of a Select Box Element Using JavaScript
Why Is "Element.Innerhtml+=" Bad Code
Insert Ellipsis (...) into HTML Tag If Content Too Wide
How to Stop a Web Page from Scrolling to the Top When a Link Is Clicked That Triggers JavaScript
How to Loop Through Selected Elements With Document.Queryselectorall