Moishy
Moishy

Reputation: 3648

jquery targeting the next character

Im trying to target the next '.' in a heading using jquery.

so right now the heading is

<h1 class="page-head">Explore. Think. Connect.</h1>

and my jquery is

 $(h1.page-head:contains(.)').each(function(){
  $(this).html(
    $(this).html().replace('.','<span class=\'nice-point\'>&#46;</span>')
  );
});

I was wondering how to target the other 2 '.' separately to add styling to them.

any help would be greatly appreciated!

Upvotes: 0

Views: 152

Answers (2)

Mithun Satheesh
Mithun Satheesh

Reputation: 27845

if you want to apply specific styles to each occurrence that comes up, you can queue up the styles you wish to apply in the order of the dots appearing in the text.

like.

$("h1.page-head:contains(.)").each(function(){

  newHTML = $(this).html()
  .replace('.','<span style=\'color:#F00;\'>&#46;</span>')
  .replace('.','<span style=\'color:#40F;\'>&#46;</span>')
  .replace('.','<span style=\'color:#0F4;\'>&#46;</span>')    

  $(this).html(newHTML);


});

here is a demo fiddle

The above example applies style=\'color:#F00;\' to the first dot, style=\'color:#40F;\' to the second dot, style=\'color:#0F4;\' to the third dot respectively. I think this is what you meant by separately adding styles to each dot. Sorry if i am wrong.

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359776

Something like this, using the overload of .html() which accepts a function:

$('h1.page-head:contains(.)').html(function (index, oldHtml) {
    return oldHtml.replace(/\./g, '<span class="nice-point">&#46;</span>');
});

If you want to do something different for each . in the oldHtml, you can get fancier, since replace() accepts a function as well, or you can use any other desired string manipulation:

$('h1.page-head:contains(.)').html(function (index, oldHtml) {
    // equivalent to the code above; just an example
    return oldHtml.split('.').join('<span class="nice-point">&#46;</span>');
});

Upvotes: 2

Related Questions