user2678018
user2678018

Reputation: 377

Count words in DOM string

I have the following HTML string:

<div><p>Hello <b>how are</b> you?</div>

I would like to loop the HTML string DOM and wrap each word with a span tag and the word number as id so result will be like this:

<div><p><span id="word-1">Hello</span> <b><span id="word-2">how</span> <span id="word-3">are</span></b> <span id="word-4">you?</span></div>

I've tried to use the JQuery method $.parseHTML but no luck to count the words because DOM node value can contain more than one word in it..

In addition, if inside the word there is inline tags such <b> / <i> so from DOM point of view each tag has a different node value even when its the same word)

Any idea how to solve this issue? how to count words inside a HTML DOM string?

Thanks

Upvotes: 1

Views: 307

Answers (2)

Rashmin Javiya
Rashmin Javiya

Reputation: 5222

Try this.

HTML

<div id="content">
  <div><p>Hello <b>how are</b> you?</div>
</div>

Script

var textNodes = $("#content *").contents().filter(function() {
    return this.nodeType === 3;
});

var counter = 1;
for(var i = 0;i<textNodes.length;i++)
{
    var val = $(textNodes).eq(i).text();
  var words = val.split(" ");
  var final = "";

  for(var j = 0;j<words.length;j++)
  {
    if(words[j].trim() != "")
    {
        final += "<span id='"+ counter +"'>"+ words[j] +" </span>";
      counter++;
    }
  }

  $($(textNodes)[i]).replaceWith(final);
}

Jsfiddle Link

Upvotes: 1

Sachin Aryal
Sachin Aryal

Reputation: 801

As of my understanding of your question this should work.

var allText = $("body").text().replace(/<[^>]*>/g, "");
var words = allText.split(' ');
for(var i=0;i<words.length;i++)
{
  $(div).append("<span id = 'word-'"+i+">"+words[i]+"</span>")
}

Upvotes: 0

Related Questions