Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Find and Wrap Ampersands

Load this plugin. Then:

$("body *").replaceText( /&/gi, '<b class="ampersand">' + '&' + '</b>' );

Change the selector as needed. That one is pretty intense.

Now you have a class name you can use to style them specially.

.ampersand {
   font-family: Baskerville, Some Other Cool Font, Serif;
   font-style: italic;
}

Reference URL

Comments

  1. Just a note, but the snippet is missing the HTML that surrounds the ampersand with an element with a class of ampersand.

  2. I don’t think you’re escaping your HTML correctly in the example above..

  3. Hi Chris !

    Whouldn’t this become a problem when you have special unicode chars like ×, < or whatever ? Will it break those chars ?

  4. JQuery .highlight() text plugin:

    jQuery.fn.highlight = function(str, className) {
        var regex = new RegExp(str, "gi");
        return this.each(function() {
            $(this).contents().filter(function() {
                return this.nodeType == 3 && regex.test(this.nodeValue);
            }).replaceWith(function() {
                return (this.nodeValue || "").replace(regex, function(match) {
                    return "<span class=\"" + className + "\">" + match + "</span>";
                });
            });
        });
    };

    http://jsfiddle.net/tovic/kfqJu/1/

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```