I want to highlight elvis presley .
<div id="test">
<p>elvis</p>
<p id="tag1">my name is elvis</p>
<p id="tag2">presley</p>
</div>
With js you can try something this:
js
var elvis = document.getElementsByTagName('p')[0];
var presley = document.getElementById("tag2")
elvis.style.color = "blue";
presley.style.color = "blue";
assuming you will always want the last words of tag1
and tag2
.
JS
This finds the last word in both tag1
and tag2
then adds a span
with the class .highlight
$("#tag1,#tag2").html(function(index, old) {
return old.replace(/(\b\w+)$/, '<span class="highlight">$1</span>');
});
CSS
.highlight {
background:yellow;
}
Using this JS as inspiration, it would be easy to manipulate the text similarly.
You can see the demo here http://jsfiddle.net/5L4kW/1/
$("document").ready(function(){
highlightText('elvis');
highlightText('presley');
})
function highlightText(val)
{
var src_str = $('div').html();
var term = val;
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");
$('div').html(src_str);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.