tags:

views:

89

answers:

2

In the method below I can search divs with a class of bar for the text foo and underline the text contained within:

function UnderlineText() {
    $(".bar").filter(":contains(foo)").css("text-decoration", "underline");
}

But I would like to pass a parameter to the method instead containing the string foo.

I have tried various permutations as seen in a previous question about the deprecated .contains

but I can't get it to work.

What is the best way to achieve this?

function UnderlineText(searchText) {
    $(".bar").filter(":contains(*searchText*)").css("text-decoration", "underline");
}
+3  A: 
function UnderlineText(searchText) {
    $(".bar").filter(":contains("+searchText+")").css("text-decoration", "underline");
}

would solve the problem.

Reigel
Yes this works great, thanks. It must have been my combination of single and double quotes that was preventing it from working for me.
Nicholas Murray
A: 

Even if you manage to get the selector working, you will select the whole containing element (p, span, div, etc.), so using a simple css() call will end up underlining the whole block of text. To underline the specific part, you'll have to use something like:

function underline(query) {
  $('.bar').filter(':contains("' + query+ '")').each(function() {
    var html = $(this).html();
    html = html.replace(query, '<span style="text-decoration: underline">' + query + '</span>';
    $(this).html(html);
  });
}

This is still not that good, since it might replace the query while it's in an attribute or somesuch, but it's a step towards getting stuff underlined separately.

Max Shawabkeh
Well, I certainly think this is very good. Perhaps there is a more elegant solution but underlining just the searched for text is an excellent idea.
Nicholas Murray