Daniel Etheve Daniel Etheve - 1 year ago 71
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 Source

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 {

<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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download