Amar Syla
Amar Syla

Reputation: 3653

Get text inside an HTML element, store it in a variable and add class to all the other matches in the DOM

I am trying to achieve this:

I have this code:

<h1>Search results for "<span>photoshop</span>"</h1>

And, I have another code like this in the same page:

<p>Photoshop is the best photo editor in the world</p>

With jQuery or pure JavaScript, I want to get the word within the span which changes dynamically, store it in a variable, and wrap every other 'photoshop' word in the document with a 'highlighted' class. How can I do this?

Upvotes: 1

Views: 1498

Answers (2)

ostapische
ostapische

Reputation: 1592

You can try to use jQuery Highlight Plugin.

Example there:

HTML:

<input onkeyup="setNewSearch(this);" />  
<h1>Search results for "<span id="search"></span>"</h1>  
<!-- text -->  

Javascript:

function setNewSearch(input){
    var value = $(input).val();
    $("#search").html(value);
    $("body").unhighlight();
    $("body").highlight(value);
}  

Upvotes: 1

Barbara Laird
Barbara Laird

Reputation: 12717

You can use a regular expression and jQuery's html() function to find and replace all occurances of a word with that word wrapped in a span.

<h1>Search results for "<span id="search">Photoshop</span>"</h1>

var theWord = $('#search').text(),
    patt=new RegExp('\\b(' + theWord + ')\\b', 'gi');

$('body').html($('body').html().replace(patt,'<span class="highlight">$1</span>'));

(use 'gi', if you want it to be global and case insensitive)

http://jsfiddle.net/EBWQX/2/

and if you can't give the span an id, maybe selecting $('h1 span') would be specific enough (depending on your code)

Upvotes: 3

Related Questions