简体   繁体   中英

wrap every odd word in span tag jquery

I want to be able to wrap every odd word in span tag but exclude the first word, I found some code online where the code wrapped the second word in a span tag at https://codepen.io/ShadyThemes/pen/OpNGjr but then found another example that wrapped the first, third and fifth word in a span tag at http://jsfiddle.net/davidThomas/buNYU/ which is ok but would like to exclude the first word

Below is what I currently have

var words = $('h5.introsubtitle').text().split(' ');
   var numWords = words.length;
      for (i=0; i<numWords; i++) {
         if (i%2 == 0) {
            words[i] = '<span>' + words[i] + '</span>';
         }
       }

      $('h5.introsubtitle').html(words.join(' '));

What I currently have is below

<h5 class="introsubtitle"><span>COMPUTER</span> REPAIR <span>FAST</span> AND <span>SECURE</span>

What I am trying to achieve is the following

<h5 class="introsubtitle">COMPUTER REPAIR <span>FAST</span> AND <span>SECURE</span></h5>

Did you tried

.class:nth-child(odd) {
...
}

If you only need the SPANs for styling I would recommend to wrap each word in a span and do the styling in CSS (as was also stated in another answer).

 var words = $('h5.introsubtitle').text().split(' '); var numWords = words.length; for (i = 0; i < numWords; i++) { words[i] = '<span>' + words[i] + '</span>'; } $('h5.introsubtitle').html(words.join(' '));
 body { font-family: Helvetica; } h5.introsubtitle span:nth-child(odd) { color: blue; } h5.introsubtitle span, h5.introsubtitle span:first-child { color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h5 class="introsubtitle">COMPUTER REPAIR FAST AND SECURE </h5>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM