jQuery addClass example
Change class name on click in jQuery
HTML
<div class="container">
<form class="form-inline">
<label class="sr-only" for="search">Search</label>
<div class="input-group">
<input id="search" type="text" class="form-control" placeholder="Highlight in text">
<span class="input-group-btn">
<button class="btn btn-secondary" id="searchButton" onclick="selectText()" type="button">Search</button>
</span>
</div>
</form>
<div class="search-content" id="search-content">
<h2>Perceived end knowledge certainly day sweetness why cordially</h2>
<p>As collected deficient objection by it discovery sincerity curiosity. Quiet decay who round three
world whole has mrs man. Built the china there tried jokes which gay why. Assure in adieus wicket it
is. But spoke round point and one joy. Offending her moonlight men sweetness see unwilling.
Often of it tears whole oh balls share an.</p>
<p>Unpacked reserved sir offering <strong>bed judgment may and quitting speaking</strong>. Is do be
improved raptures offering required in replying raillery. Stairs ladies friend by in mutual an no.
Mr hence chief he cause. Whole no doors on hoped. Mile tell if help they ye full name.</p>
<p>Behaviour we improving at something to. Evil true high lady roof men had open. To
<b class="bold">projection</b> considered it precaution an melancholy or. Wound young you thing
worse along being ham. Dissimilar of favourable solicitude if sympathize middletons at. Forfeited
up if disposing perfectly in an eagerness perceived necessary. Belonging sir curiosity discovery
...
CSS
.highlight {
background:yellow;
}s
JavaScript
$(document).ready(function () {
$("#searchButton").click(function () {
searchHighlight($("#search").val());
});
});
function searchHighlight(searchText) {
if (searchText) {
var searchExp = new RegExp(searchText, "ig");
var content = $('p').text();
var matches = content.match(searchExp);
if (matches) {
$('p').html(content.replace(searchExp, function(match) {
return "<span class='highlight'>" + match + "</span>";
}));
} else {
$(".highlight").removeClass(".highlight");
}
} else {
$(".highlight").removeClass(".highlight");
}
}