Talha
Talha

Reputation: 350

select each word and adding a class jquery

<div class="icheckbox_line-blue checked" type="checkbox">
<div class="icheck_line-icon"></div>
Word  5   Word   Word
<ins class="iCheck-helper"></ins>
</div>

I want to add a class to the each of the first 3 words here. I'm counting "5" as a word here as well. I use the following js to add span to each one of them

  $(function() {
    var all_words=$(".icheckbox_line-blue").text().split(' ');
    $(".icheckbox_line-blue").html("");
    $.each(all_words, function(i,val){
    $('<span/>').text(val +" ").appendTo(".icheckbox_line-blue");
    });
    });

But the result is a bunch of spans created, some of them around the word and some of them empty. As you see there are other elements inside the div like "<div class="icheck_line-icon"></div>" that doesn't need to get a span. Trying to figure our how to reach the first three words and leave the rest. Also the words are dynamic so I can't select them by their value.

Upvotes: 0

Views: 1025

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206505

jsBin demo

$(function() {

  $('.icheckbox_line-blue').each(function(){ // EACH!!!

    var parts = $.trim( $(this).text() ).split(/\s+/g);
    var newHTML = "";
    $.each(parts, function(i,val){
       newHTML += "<span>"+ val +"</span>";
    });

    $(this).html(newHTML); // Append only once (10x faster)

  });

});

Make sure to $.trim() your contents and split by /\s+/g one or more whitespaces / globally.
Also notice the way you can use $('<span/>', {text: val+' '})

Upvotes: 2

BigSpicyPotato
BigSpicyPotato

Reputation: 739

Here is an updated function and the html code. I have put the words into there own div so they can be accessed and split up easily.

html

<div class="icheckbox_line-blue checked" type="checkbox">
<div class="icheck_line-icon"></div>
<div id="word_list">Word 5 Word Word</div>
<ins class="iCheck-helper"></ins>
</div>

js

$(function() {
var all_words = $("#word_list").text().split(' ');
$(".icheckbox_line-blue").html("");
for (var x = 0; x < all_words.length; x++) {
    if (x < 3) {
        $('<span/>').text(all_words[x] + " ").appendTo(".icheckbox_line-blue");
    }

    else {
        $(".icheckbox_line-blue").append(all_words[x] + " ")
    }
}
});

this will also only select the first 3 words and put an tag on them and the rest will be put in as normal words.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388416

Try

$(function () {
    $(".icheckbox_line-blue").contents().each(function () {
        if (this.nodeType == 3 && $.trim(this.nodeValue)) {
            $(this).replaceWith(this.nodeValue.replace(/([^\s]+)/g, '<span class="myclass">$1</span>'))
        }
    })
});

Demo: Fiddle

Upvotes: 3

Related Questions