Question

I have no back-end access to this html so JavaScript is my only option.

I tried using the .before() and .after() functions but I can only get it before the first phone umber and after the last one.

Below is what it looks like.

<div id="phonenumber">888-888-888 888-888-8888</div>

This is what I'm trying to achieve.

<div id="phonenumber">
<span>888-888-888</span> 
<span>888-888-8888</span>
</div>
Was it helpful?

Solution

Like this?

$('#phonenumber').html(function(_, html){ //Use html callback function
    return $.map(html.split(/\s+/), function(val){ // split the current text based on spaces and use $.map to get the html span.
        return $('<span/>',{text:val}); //construct the span.
    });
});

Demo

This is the output:

<div id="phonenumber">
      <span>888-888-888</span>
      <span>888-888-8888</span>
</div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top