Dan Ovidiu Boncut
Dan Ovidiu Boncut

Reputation: 3165

Select every word and give it another color

How can I select every word in a page, reverse it and give it another color?

What I tried for now:

jQuery('*').each(function(){
    var text = jQuery(this).text().split(' '),
        len = text.length,
        result = []; 

    for( var i = 0; i < len; i++ ) {
        result[i] = '<span style="color: green;">' + text[i].split("").reverse().join("") + '</span>';
    }
    jQuery(this).html(result.join(' '));
});   

But I am pretty far from what I need. Any clues?

Upvotes: 0

Views: 300

Answers (2)

Matt Ellen
Matt Ellen

Reputation: 11592

This splits up the text into words (based on space, but you could use a regular expression, if you want something more complicated), then reverses the word, assigns each of them a colour and writes that to the result div.

var main = document.getElementById('main');
var result = document.getElementById('result');

var text = main.textContent;

var words = text.split(' ');

var colours = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'black'];

for(var wi = 0; wi < words.length; wi++)
  {
    if(words[wi] !== '')
      {
        var c = colours[Math.floor(Math.random() * colours.length)];
        result.innerHTML += '<span class="'+c+'">'+words[wi].split("").reverse().join("")+'</span> ';
      }
  }
span.red
{
  color:#ff0000;
}

span.green
{
  color:#00ff00;
}

span.blue
{
  color:#0000ff;
}

span.cyan
{
  color:#00ffff;
}

span.magenta
{
  color:#ff00ff;
}

span.yellow
{
  color:#ffff00;
}

span.black
{
  color:#000000;
}
<div id="main">
  There is a bunch of words here. Maybe we can split them up and change their colours.
</div>
<div id="result">
</div>

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You are trying to replace the entire contents of the elements, it has a problem when you try to replace the root nodes

//the main point here is you need to replace only the contents of the text node, not all the html parts
jQuery('*').contents().each(function () {
    //not a text node or there is no content to replace
    if (this.nodeType != 3 || !this.nodeValue.trim()) {
        return;
    }

    //replace the value of the text node
    $(this).replaceWith(this.nodeValue.replace(/\w+/g, function (part) {
        return '<span style="color: green;">' + part.split("").reverse().join("") + '</span>'
    }))
});

Demo: Fiddle

Upvotes: 1

Related Questions