How to target specific letter/word with jquery?

后端 未结 3 685
执念已碎
执念已碎 2021-01-19 06:17

As a mere example, I want to apply the class \"fancy\" to all occurrences of the sign \"&\" in the document.

The C

相关标签:
3条回答
  • 2021-01-19 06:57

    There's a "highlight" plugin that does almost exactly what you describe:

    http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html

    0 讨论(0)
  • 2021-01-19 06:58

    Regex is commonly used for this:

    http://chirale.wordpress.com/2009/07/04/character-substitution-on-jquery/

    http://forum.jquery.com/topic/how-to-select-specific-characters-and-replace-them

    0 讨论(0)
  • 2021-01-19 07:05

    This isn't something that jQuery is generally helpful with--it works more at the node level than the text/html level. However, this might help (source):

    $('p:contains(&)').each(function(){
      $(this).html(
        $(this).html().replace('&amp;','<span class=\'fancy\'>&amp;</span>')
      );
    });
    

    Obviously if you can restrict the initial search to something better than all paragraphs, it'd perform better. You should also test it to see if the :contains filter actually helps.

    It's not pretty but it seems to work.

    0 讨论(0)
提交回复
热议问题