1

the following code I have written for inline styling, instead of that i need to provide the class from from different .css file using jquery .addClass method. How Can I do that?

$(keywords).each(function(){                 
        var pattern = new RegExp("("+this+")", ["i"]);              
        var rs = "<span style='background-color:#FF6666;font-weight:bold'>$1</span>";  
        if(el.length > 0){
            el.html(el.html().replace(pattern, rs));
        }

    });    
1
  • You don't have to replace like that, before I suggest a solution, can you please show the HTML code where you are trying to do this? Or what exactly is keywords, el in your code. Commented Feb 13, 2013 at 12:15

2 Answers 2

1
$(keywords).each(function(el){                 
     $(el).addClass('yourClass');
});  
Sign up to request clarification or add additional context in comments.

1 Comment

modify it to this $(el).addClass('yourClass').attr("style", ""); and that'll clear the inline style after adding class.
0

If you need to style your newly created span element just replace style="..." with class="className", no need to use addClass

$(keywords).each(function(){                 
        var pattern = new RegExp("("+this+")", ["i"]);              
        var rs = "<span class="class">$1</span>";  
        if(el.length > 0){
            el.html(el.html().replace(pattern, rs));
        }
    });

Or, if you have to set class to a different object, just do

$("selector").addClass("className")

3 Comments

thanks a lot , the var rs = "<span class="class">$1</span>"; thing worked.
Further to this I m facing one more issue- by applying above changes i am able to highlight the first occurrence keyword but not the subsequent once.
try to replace new RegExp("("+this+")", ["i"]); with new RegExp("("+this+")", "ig");` (g means global search, do not stop at first match)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.