jquery: Count number of words in data attribute - javascript

I have some elements with data attribute containing some tags.
I need to count number of each element's tags.
like this:
<div data-tags="foo bar something else">
some text
</div>
<div data-tags="foo bar">
some text
</div>
<div data-tags="foo">
some text
</div>
<div data-tags="">
some text
</div>
and I want to do something like this:
$('div[data-tags]').each(function(){
var tags = $(this).data('tags'),
count = tags.split(' ').length;
$(this).css({marginLeft: (20 * count)});
});
But in this way the count will be 1 for both elements with data-tags="" and data-tags="foo" since the result for split would be like this:
"".split(' '); //[""]
"foo".split(' '); //["foo"]
and length of both of these is 1.
The only way I can think of is to add a condition and do the stuff if the split result was not [""]. But it doesn't look like a good idea. Or not the best at least.
I want to know if anyone has a better idea. thanks.

You can use regexp match instead of simple split:
$('div[data-tags]').css('marginLeft', function() {
var tags = $(this).data('tags');
return (tags.match(/\w+/g) || []).length * 20;
});
Demo: http://jsfiddle.net/dqfx0wun/2/

One way is to use Array.prototype.filter(), and String.prototype.trim(), to remove empty white-space-only array-elements:
$('div[data-tags]').each(function() {
var tags = $(this).data('tags'),
count = tags.split(' ').filter(function (word) {
return word.trim().length;
}).length;
$(this).css({
marginLeft: (20 * count)
});
});
div[data] {
border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-tags="foo bar something else">
some text
</div>
<div data-tags="foo bar">
some text
</div>
<div data-tags="foo">
some text
</div>
<div data-tags="">
some text
</div>
Or, alternatively, test for the length of the tags variable; zero is a falsey value:
$('div[data-tags]').each(function() {
var tags = $(this).data('tags'),
count = tags.split(' ').length;
$(this).css({
marginLeft: tags.length ? (20 * count) : 0
});
});
div[data] {
border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-tags="foo bar something else">
some text
</div>
<div data-tags="foo bar">
some text
</div>
<div data-tags="foo">
some text
</div>
<div data-tags="">
some text
</div>
References:
Array.prototype.filter().
String.prototype.trim().

Related

Show and Hide the text with stars on clicking the button

I have a paragraph tag with number init. I want to replace the numbers with stars/round circles on clicking the button beside it. Also, I am attaching a screenshot to which I want to apply the concept(on clicking the eye icon the Patient Id should be replaced with round circles and vice versa). Attaching the code which I have tried. Your solutions are very important for me in learning the things. TIA
enter image description here
$('.hide-id').on('click', function () {
$('.patient-id-content').attr('type', 'password');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<p>
<span class="patient-id-content" type="text">34324345</span>
<button class="hide-id">
Hide
</button>
</p>
</div>
Here is what you need.
$(".hide-id").on("click", function () {
var span = $(".patient-id-content");
var spanText = span.text();
if (!spanText.indexOf("*")) {
$(".patient-id-content").text(span.attr("data-oldText"));
return;
}
var starText = "";
for (let i = 0; i < spanText.length; i++) starText += "*";
$(".patient-id-content")
.attr("data-oldText", spanText)
.text(starText);
});
working example on jsfiddle: https://jsfiddle.net/ynojkf0q/
So your jQuery code from the OP was not correct. You have what you want as the password in a span and are applying a type attribute to that.
If you check the MDN Docs, you will learn that there is no type attribute for a span, as spans only support Global Attributes. The input element uses both the type: text and type: password, see the docs here.
But if you want to have the span as your element, you can change your jQuery event handler to the following: .toggleClass('hidden'); and create a hidden CSS class with the properties display: none;
$('.hide-id').on('click', function () {
$('.patient-id-content').toggleClass('hidden');
});
.hidden { display: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<p>
<input class="patient-id-content" type="text" value="34324345">
<button class="hide-id">
Hide
</button>
</p>
</div>
This is a simple solution for the functionality you want. It will need more styling to get it to look exactly the the example you provided above.
HTML
<div class="container">
<p>
<input class="patient-id-content" type="password" value="34324345">
<button id="pass-toggle" class="hide-id" onclick="toggleShowPassword()">
Show
</button>
</p>
</div>
JS
let passwordVisible = false;
function toggleShowPassword() {
let inputType = 'password';
passwordVisible = !passwordVisible;
if (passwordVisible) {
inputType = 'text';
$('#pass-toggle').addClass( "show-id" ).text( 'Hide' );
} else {
$('#pass-toggle').removeClass( "show-id" ).text( 'Show' );
}
$('.patient-id-content').attr('type', inputType);
CSS
.patient-id-content {
border: 0;
}
You could do something like:
to have hidden by default:
<span class="patient-id-content" type="text" data-patient-id="34324345" data-visible="false">********</span>
to show by default:
<span class="patient-id-content" type="text" data-patient-id="34324345" data-visible="true">34324345</span>
$('.hide-id').on('click', function () {
const patientId = $(this).prev('span'); // dependent on this DOM placement
const patientIdValue = patientId.attr('data-patient-id');
const isShowing = patientId.data('visible');
const valueToShow = isShowing ? '********' : patientIdValue;
patientId.text(valueToShow);
patientId.data('visible', !isShowing)
});
Included a JS Fiddle: https://jsfiddle.net/w7shxztp/20/
I have fixed the issue with the below solution:
$(".icofont-eye").on("click", function() {
$('#Patient-id-icon-element').toggleClass('icofont-eye-blocked');
$('#Patient-id-icon-element').toggleClass('icofont-eye');
var patientIdcontent = $(".patient-id-content");
var patientIdcontentText = patientIdcontent.text();
if (patientIdcontentText.indexOf("*")) {
$(".patient-id-content").text('***************');
} else {
$(".patient-id-content").text('3d4532403d453240');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row mt-1">
<div class="col-4 text-right mychart-label">Patient ID</div>
<div class="col-8 section-content">
<span class="patient-id-content">****************</span> <span class="patient-id-icon">
<a class="icofont icofont-eye cl-icon-1-point-3x mt-1" id="Patient-id-icon-element" type="button">Show</a>
</span>
</div>
</div>

Displaying a message when jQuery filter returns nothing

I found code online that filters elements by their text content.
How can I display a message when there is no match?
$("button").click(function() {
var value = $(this).data('value').toUpperCase();
$("div").filter(function(index) {
$(this).toggle($(this).text().indexOf(value) > -1)
});
});
<button>example</button>
You're using filter() to toggle each item based on state, like using each(). But one advantage of filter() is that you can return a reduced selection and count the items it contains. That value can determine whether a "no match" message should be displayed.
... the .filter() method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against each element; all elements matching the selector will be included in the result. -- filter().
For each element, if the function returns true (or a "truthy" value), the element will be included in the filtered set; otherwise, it will be excluded. -- Using a Filter Function
So, instead of toggling items directly from the filter call, consider returning a Boolean measure of whether the current item is a match. Save the resulting filtered selection in a variable. After filtering, you can toggle that selection as a whole:
var $filtered = $items.filter(function() {
return $(this).text().indexOf(value) > -1;
});
$items.toggle(false);
$filtered.toggle(true);
This hides all items and then shows only the filtered items.
You might even consider some fading animation:
$items.hide(250);
$filtered.stop(true,false).show(250);
Then you can reference the filtered selection's length.
If it's zero, show the "not found" message:
var hasMatches = $filtered.length;
if (hasMatches) {
// there were matches.
} else {
// no matches.
}
You can also pass a selector to a filter. jQuery's :contains() selector selects "all elements that contain the specified text", which makes a nice choice.
Working Example:
var $items = $('.item');
var $none = $('#none');
var fade = 250;
function filterContent() {
// get word from value of clicked button.
var word = this.value;
// hide items; filter; show filtered; count matches
var hasMatches = $items
.hide(fade)
.filter(':contains(' + word + ')')
.stop(true, false)
.show(fade)
.length;
// if no matches, show message.
if (hasMatches) {
$none.hide(fade);
} else {
$none.show(fade);
}
}
$('button').on('click', filterContent);
#none {
display: none;
color: darkred;
}
#buttons {
margin: 1em 0 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">Here is some text.</div>
<div class="item">Here is some other text.</div>
<div class="item">Here is some other different text.</div>
<div class="item">Here is something else.</div>
<div class="item">Here is some additional text.</div>
<div id="none">No matches found.</div>
<nav id="buttons">
<button type="button" value="">all</button>
<button type="button" value="text">text</button>
<button type="button" value="other">other</button>
<button type="button" value="additional">additional</button>
<button type="button" value="bazooka">bazooka</button>
</nav>
Another way:
If you prefer, you can toggle inside the filter as long as you still return the state Boolean from the function. I suggest making a separate function to pass to the filter. In this case, toggleItem() determines the state of an item (match or non-match), toggles the item according to that state, and returns the state.
var $items = $('.item');
var $none = $('#none');
function toggleItem(word) {
return function(k, el) {
var $item = $(el);
var state = $item.text().indexOf(word) > -1;
$item.toggle(state);
return state;
}
}
function filterContent() {
// get word from value of clicked button.
var word = this.value;
// filter while toggling and count result.
var hasMatches = $items
.filter(toggleItem(word))
.length;
// if no matches, show message.
$none.toggle(!hasMatches);
}
$('button').on('click', filterContent);
#none {
display: none;
color: darkred;
}
#buttons {
margin: 1em 0 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">Here is some text.</div>
<div class="item">Here is some other text.</div>
<div class="item">Here is some other different text.</div>
<div class="item">Here is something else.</div>
<div class="item">Here is some additional text.</div>
<div id="none">No matches found.</div>
<div id="buttons">
<button type="button" value="">all</button>
<button type="button" value="text">text</button>
<button type="button" value="other">other</button>
<button type="button" value="additional">additional</button>
<button type="button" value="bazooka">bazooka</button>
</div>
In my opinion, this is a bit harder to read and not as clear as the chained "hide,filter,show,length" commands, but that's somewhat a matter of style. You can see that there are many ways to bake this cake!
This one's pretty short and sweet:
var $none = $("#none");
var $items = $(".item");
$("button").click(function() {
var value = $(this).data('value');
$items.each(function() {
$(this).toggle($(this).text().indexOf(value) > -1);
});
$none.toggle(!$items.filter(':visible').length);
});
#none {
display: none;
color: darkred;
}
#buttons {
margin: 1em 0 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">Here is some text.</div>
<div class="item">Here is some other text.</div>
<div class="item">Here is some other different text.</div>
<div class="item">Here is something else.</div>
<div class="item">Here is some additional text.</div>
<div id="none">No matches found.</div>
<nav id="buttons">
<button type="button" data-value="">all</button>
<button type="button" data-value="text">text</button>
<button type="button" data-value="other">other</button>
<button type="button" data-value="additional">additional</button>
<button type="button" data-value="bazooka">bazooka</button>
</nav>
You can create a variable to count match item.
$("button").click(function(){
var value = $(this).data('value').toUpperCase();
var count = 0;
$("div").filter(function(index) {
if($(this).text().indexOf(value) > -1) count++;
$(this).toggle($(this).text().indexOf(value) > -1)
});
if(count == 0) alert('Not match');
});
$("button").click(function(){
var value = $(this).data('value').toUpperCase();
var count = 0;
$("div").filter(function(index) {
if($(this).text().indexOf(value) > -1) count++;
$(this).toggle($(this).text().indexOf(value) > -1)
});
if(count == 0) alert('Not match');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>TEST1</div>
<div>example</div>
<div>test1</div>
<button data-value='test1'>example</button>
filter() returns the value. Check if the length is 1 or more.
$(".filter").click(function() {
var value = $(this).text(); //Get the text of the button
var result = $("div").hide().filter(function(i, o) { //Hide All and filter
return $(o).text().includes(value); //Return true if the content of div contains text of the button
}).show(); //Show all result
if (result.length) { //Check the length of the result
//Found match/es
$(".msg").text('');
} else {
//No match
$(".msg").text(`${value} not found`);
}
});
$(".show-all").click(function() {
$("div").show();
});
.msg {
border: 1px solid black;
}
div {
background-color: pink
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="msg"></span>
<br /><br />
<div> apple </div>
<div> orange </div>
<div> rock melon</div>
<div> pineapple </div>
<div> pineapple pie</div>
<br /><br />
<button class="filter">example</button>
<button class="filter">pineapple</button>
<button class="filter">rock</button>
<br /><br />
<button class="show-all">Show all</button>

Javascript - Input text and output to multiple areas

I'm trying to input text in a field, and have it output to multiple fields.
Currently, it only outputs to the first field.
Here's the input:
<form class="form" onchange="myFunction()">
<div class="mb-4">
<p>The quick sly fox jumped over the <input id="object" class="inline borderless-input"></p>
</div>
</form>
JS controlling the output:
function myFunction()
{
//Object
var x = document.getElementById("object");
var div = document.getElementById("objectDisplay");
div.innerHTML = x.value;
}
Here's a codepen I'm working with: Codepen
ID's have to be unique. Use classes and a for loop to cycle through each one and change it. This cannot be done with document.getElementById. See https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById for some basic information about document.getElementById. document.getElementsByClassName returns an array filled with existing elements with a certain class. In this case, objectDisplay. If you want to read more about that then take a look here: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName.
The new code should look like this:
function myFunction() {
//Object
var x = document.getElementById("object");
var div = document.getElementsByClassName("objectDisplay");
for (i = 0; i < div.length; i++) {
div[i].innerHTML = x.value;
}
}
.container {
padding: 10px;
}
.text-strong {
font-weight: bold;
}
.inline {
display: inline;
}
.borderless-input {
background-color: transparent;
border-style: solid;
border-width: 0px 0px 1px 0px;
padding: .5rem .75rem;
text-align: center;
}
<div class="container">
<div class="row">
<div class="col-lg-12">
<form class="form" onchange="myFunction()">
<div class="mb-4">
<p>The quick sly fox jumped over the <input id="object" class="inline borderless-input"></p>
</div>
</form>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h3><strong>Output</strong></h3>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<p>The quick sly fox jumped over the <span class="objectDisplay inline"></span>.</p>
<p>The quick sly fox jumped over the <span class="objectDisplay inline"></span>.</p>
<p>The quick sly fox jumped over the <span class="objectDisplay inline"></span>.</p>
</div>
</div>
</div>
<!-- For Testing Only -->
<div class="container">
<div class="row">
<div class="col-lg-10 offset-lg-1 mx-auto">
<!-- Test Here -->
</div>
</div>
</div>
Identify your inputs with class instead of id
<p>The quick sly fox jumped over the <span id="objectDisplay" class="objectDisplay inline"></span>.</p>
use this
var divs = document.getElementsByClassName("objectDisplay");
for(var i = 0; i < divs.length; i++){
divs[i].innerHTML = x.value;
}
instead of
var div = document.getElementById("objectDisplay");
div.innerHTML = x.value;
I found a similar question see the link: jQuery id selector works only for the first element.
but briefly, you're using the same ID for more than one element, try using the class selector, example document.getElementsByClassName ('your-class') or document.querySelectorAll ('your-class'), remembering that in querySelectorAll for classes: '.your-class' and Id: '# my-id'.
function myFunction(){
//Object
var x = document.getElementById("object");
var div = document.querySelectorAll(".col-lg-12 span");
for(var i = 0; i < div.length;i = i + 1){
div[i].innerHTML = x.value;
}
}
IDs are unique so you should have only one ID per page. Try changing objectDisplay to a class and then selecting them all and looping through each as below
function myFunction(el)
{
//Object
var x = document.getElementById("object");
var divs = document.querySelectorAll(".objectDisplay");
var inputValue = el.value;
for(var i=0; i < divs.length; i++){
divs[i].innerHTML = inputValue;
}
}
<form class="form">
<div class="mb-4">
<p>The quick sly fox jumped over the <input id="object" class="inline borderless-input" onchange="myFunction(this)" value=""></p>
</div>
</form>
<div class="objectDisplay"></div>
<div class="objectDisplay"></div>

Counter if word appears in div [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Take a look at my jsfiddle first.
Now, I want to create a counter everytime Scissor, Rock and Paper appears in the div #myChoice.
I have to do it like this.. so no other ways like on click whatever please.
How to do this?
if "Rock" appears in the div #myChoice
-> Rock Count: 1
-> Paper Count: 0
-> Scissor Count: 0
if "Scissor" appears in the div #myChoice
-> Rock Count: 1
-> Paper Count: 0
-> Scissor Count: 1
if "Rock" appears in the div #myChoice AGAIN
-> Rock Count: 2
-> Paper Count: 0
-> Scissor Count: 1
Thanks for your help & sorry for my latest question that nobody understood lol
Use Event delegation to handle clicks. If the user clicks on an option, then look for an associated count element and update the count. The example below uses .hasClass() to see if the element clicked on has a class name option (added to distinguish the options from other elements), parseInt() to check for a number in the count container and then isNaN() to check if the count number is actually a number (unlike an empty string).
$(document).ready(function() {
$(document).click(function(event) {
if ($(event.target).hasClass('option')) {
$('#myChoice').text(event.target.innerText);
var countElement = $('#' + event.target.id + 'Count');
if (countElement.length) {
var count = parseInt(countElement.text(), 10);
if (isNaN(count)) {
count = 0;
}
countElement.text(++count);
}
}
});
});
#myChoice {
width: 100px;
height: 20px;
border: 1px solid black
}
li {
width: 50px;
border: 1px solid black;
padding: 3px;
margin-bottom: 5px
}
li:hover {
background-color: gainsboro;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<div id="scissor" class="option">Scissor</div>
</li>
<li>
<div id="rock" class="option">Rock</div>
</li>
<li>
<div id="paper" class="option">Paper</div>
</li>
</ul>
<br />
<div id="myChoice">
</div>
<br />
<div id="counter">
<p>Scissor Count:
<span id="scissorCount"></span>
</p>
<p>Rock Count:
<span id="rockCount"></span>
</p>
<p>Paper Count:
<span id="paperCount"></span>
</p>
</div>
Is this what you want ?
var helloLength = $('#container:contains("Hello")').length;
if(helloLength >= 1) {
$("#counter").text("Hello " + helloLength + " times");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"> Hello </div>
<div id="counter"> Hello: /*here the number*/ times </div>
If you want to count the number of hello, you should use class instead of id: like this:
var helloLength = $('.container:contains("Hello")').length;
if(helloLength >= 1) {
$("#counter").text("Hello " + helloLength + " times");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"> Hello </div>
<div class="container"> Hello </div>
<div class="container"> Random div </div>
<div class="container"> Hello </div>
<div class="container"> Hello </div>
<div id="counter"> Hello: /*here the number*/ times </div>
You can achieve this by using a regular expression and the match() method to find the number of occurrences of 'Hello' within your string. From there you can use text() on a span within the #counter element to show the value. Try this:
var re = /hello/gi;
var count = ($('#container').text().match(re) || []).length;
$('#counter .count').text(count);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"> Hello hello </div>
<div id="counter"> Hello: <span class="count"></span> times </div>
I just want to count +1 inside of a div everytime the other div contains the word Hello.
I took this to mean you want to count the number of times the word "Hello" is in the first div, so here's a simple loop to do that.
// create an array out of the text of #container using spaces to delimit
var text = $('#container').text().split(" ");
var count = 0;
// loop through the array of text and check to see if each word is "Hello"
for (var i = 0; i < text.length; i++) {
if (text[i] === "Hello") {
count++;
}
}
$('#counter').text("Hello: " + count + " times");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">Hello Hello Hello Hello</div>
<div id="counter"></div>
You can just use this simple function countWords()
function countWords(str){return (str.match(/Hello/g) || []).length;;}
$('#counterValue').text( countWords($("#container").text()) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="container"> Hello and Hello but Hello is what I'm saying... last Hello!</div>
<div id="counter"> Hello: <span id="counterValue"></span> times </div>

How to use jquery to highlight the search keyword in search results? [duplicate]

This question already has answers here:
Search a string but ignore tag [duplicate]
(2 answers)
Closed 6 years ago.
for example, there is following html in search results, and the aa is the keyword:
<body>
<div>
<h2>aabbcc</h2>
</div>
<div>
<h2>aaeeedd</h2>
</div>
<div>
<h2>vvaapp</h2>
</div>
</body>
I want to highlight the search keyword aa in results and don't change other anything :
I try this:
var text = $('body').html().replace(new RegExp('aa','gim'),"<span class='highlight'>aa</span>");
$('body').html(text);
But all html were replaced, include the href '#aa'.
I think use the each() and text() maybe ok.
And is there better solution?
$('div a').each(function() {
var text = $(this).text();
$(this).text(text.replace('aa', 'bb'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div>
<h2>aabbcc</h2>
</div>
<div>
<h2>aaeeedd</h2>
</div>
<div>
<h2>vvaapp</h2>
</div>
</body>
Using replace and .text()
$('div a').each(function() {
var text = $(this).text();
$(this).text(text.replace(/[aa]+/g, "bb"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div>
<h2>aabbcc</h2>
</div>
<div>
<h2>aaeeedd</h2>
</div>
<div>
<h2>vvaapp</h2>
</div>
</body>
Using regex
$('#filter').on('keyup', function(event) {
var keyword = event.currentTarget.value;
highlight('a', keyword);
});
function highlight(selector, keyword) {
$(selector).each(function(index, element) {
var $element = $(element);
var original = $element.data('originalText');
if (original == undefined) {
original = $element.html();
$element.data('originalText', original);
}
$element.html(original.replace(keyword, '<span class="highlight">' + keyword + '</span>'));
});
}
.highlight {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input type="text" id="filter"/>
<div>
<h2>aabbcc</h2>
</div>
<div>
<h2>aaeeedd</h2>
</div>
<div>
<h2>vvaapp</h2>
</div>
</body>
Your best off using text.textContent()
Its easier
Remember you can still use Jquery and JS at once
I found a function to solve it! And it is working well!
//highlight the search keyword
function highlight($area,keyword) {
var re = new RegExp("(" + keyword + ")(?=[^<>]*<)","gi");
var html = $area.html().replace(re, '<span class="searchkeyword">$1</span>');
$area.html(html);
}
highlight($('body'), 'aa');

Categories