steviblaze
steviblaze

Reputation: 3

find and wrap every instance of a text character in a span using jQuery

We want to find every instance of a character (specifically, ) on a page, then wrap it in a span so we can style them. They could be within all sorts of elements, multiple times, and all over the DOM: <nav/>, <h1/>, <p/>, etc.

We've tried one method found here related to matching a string and wrapping a span around it, but it seems to only match and wrap the first instance within any given element and ignore any subsequent instances within the same element. For example, for <p>•</p> <p>•</p>, both get matched and wrapped, but <p>blah • blah • blah • blah</p>, only the first gets matched and wrapped.

Here's what we tried:

$('*:contains("•")').each(function() {
   if($(this).children().length < 1)
      $(this).html($(this).text().replace('•','<span class="bullets">•</span>'))
});

Not sure if it has something to do with the if line... that's the only part that we're fuzzy about. Not particularly invested in this approach, however, so if there is something cleaner, let's hear it!

Upvotes: 0

Views: 2380

Answers (2)

GrayB
GrayB

Reputation: 1000

$("*").each(function() { 
    if($(this).children().length==0) { 
        $(this).html($(this).html().replace(/•/g, '<span class="bullets">•</span>')); 
    } 
});

This answer is based of this question

Js Fiddle Example

Upvotes: 0

PSL
PSL

Reputation: 123739

How about this:-

Demo

$('body:contains("•")').contents().each(function () {
    if (this.nodeType == 3) {
        $(this).parent().html(function (_, oldValue) {
            return oldValue.replace(/•/g, "<span class='bullets'>$&</span>")
        })
    }
});

Try avoid using *. probably even body. Try using the outermost container as possible.

This should also work

Demo

$('body:contains("•")').contents().each(function () {
    if (this.nodeType == 1) { //Look for only element Nodes
        $(this).html(function (_, oldValue) {
            return oldValue.replace(/•/g, "<span class='bullets'>$&</span>")
        })
    }

Node Types

Upvotes: 4

Related Questions