Andrew
Andrew

Reputation: 1121

Adding Span before specific string with jQuery

Is it possible to add a HTML element before a specific string using jQuery? For example, if I have:

<h4>Men's Basketball vs. Georgetown</h4>

And I would like to make it:

<h4>Men's Basketball <span class="team">vs. Georgetown</span></h4>

Can I do that with jQuery? I have tried to use a variety of options (:contains, prepend(), html(), pop(), etc. But none of them seem to work exactly right.

Upvotes: 0

Views: 1942

Answers (4)

Travis J
Travis J

Reputation: 82267

jsFiddle Demo

Assuming that for every h4 you would like the vs. and what follows wrapped in a span, then you should iterate through each one, determine the location of vs. in the string and then wrap it in a span.

html: <h4>Men's Basketball vs. Georgetown</h4>

css: .team{ color: red; }

js:

$("h4").each(function(){
 var v = 'vs.',t = $(this), prefix, suffix;
 if(t.text().indexOf(v) > -1 ){
  prefix = t.text().substr(0,t.text().indexOf(v));
  prefix += "<span class='team'>";
  suffix = t.text().substr(t.text().indexOf(v));   
  suffix += "</span>";
  t.html(prefix+suffix);
 }
});

Upvotes: 1

Jehanzeb.Malik
Jehanzeb.Malik

Reputation: 3390

I would give the h4 an id if I were you.

$(document).ready(function(){
    var text = $('h4').html().split('vs.');

    $('h4').html(function(){
        return text[0] + '<span class="team"> vs. '+ text[1] +'</span>';
    });
});

Or if you have an Id. Lets say Id1.

$(document).ready(function(){
    var text = $('#Id1').html().split('vs.');

    $('#Id1').html(function(){
        return text[0] + '<span class="team"> vs. '+ text[1] +'</span>';
    });
});

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

You can do that :

var h4 = $('h4');
var str = 'vs. Georgetown';
h4.html(h4.text().replace(str, '<span class="team">'+str+'</span>'));

Supposing you want to wrap vs and the end of the text in all h4 elements, then you might do

$('h4').each(function(){
   var bip = $(this).text().split(/(?<vs)/);      
   if (!bip.length) return;
   $(this).html(bip[0]+'<span class="team">'+bip[1]+'</span>');
});

Upvotes: 1

Ohgodwhy
Ohgodwhy

Reputation: 50767

I would do...

var str = $('h4').split('vs.'); // team name

$('h4').html(function(){
    return str[0] + 'vs. <span class="team"> '+ str[1] +'</span>';
});

This seems a bit more of a dynamic solution than the previous answer.

Here's your working jsFiddle

Upvotes: -1

Related Questions