Daniel Etheve Daniel Etheve - 5 months ago 12
jQuery Question

Is there a way to add a class to the first word of a specific class?

i'm looking for a way to add a custom class to the first and second word of a specific class ?

My code goes like this

<h2 class="content-heading">Latest News</h2>


And i would like to have something like

<h2 class="content-heading"><span class="1">Latest</span> <span class="2">News</span></h2>

Answer

you can set the html using a function then split the innerText and map to a span.

$('.content-heading').html(function() {
  return this.innerText.split(' ').map(function(e, i) {
    return $('<span />', {
      class: 'i' + i,
      text: e
    });
  });
});
.i0 {
  color:red;  
}

.i1{
   color:blue; 
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2 class="content-heading">Latest News</h2>

NOTE: classes need to be SGML names. Therefore I have prefixed with an i in my example.

Comments