Change the color of random letters in a paragraph

I want to change the color of some random characters in the paragraph to red when I click the button. Please find my code. I have some errors in this.

$('input').click(function(){ var para = $('#para'); var position = Math.floor(Math.random()*100); var character = []; var i=0 while ( i <= 30 ) { character[i] = para.html().substr(position*(i+1), 1); i++; } $.each(character, function() { character.css('color','red'); }); }); 

First of all, I created an array that would contain 30 random letters from a paragraph. Then I used each() to iterate over each of the elements of the array to apply the css property. But a message appears in the console window stating that the object does not have a 'css' method

What am I doing wrong?

+4
source share
2 answers

First of all, the CSS method will only work on jquery objects. You have strings in an array of characters. The css method will not work with strings.

Secondly, each of your methods is spelled incorrectly. It should be like

 $.each(character, function(index, value) { // Do something }); 

For your operator, the problem is to change the color of some random characters in your string. Here is the fiddle . Try it.

Here is the code:

 $('input').click(function(){ var para = $('#para'); var charArray = $('span', para); // case: No span (Initial String) if (charArray.length === 0) { var html = para.html(); var newArr = []; var len = html.length; for (var i=0; i<len; i++) { newArr.push('<span>' + html[i] + '</span>'); } html = newArr.join(''); para.html(html); charArray = $('span', para); } // Reset all spans $.each(charArray, function(i, value) { value.style.color = ''; }); var paralen = charArray.length; for (var i=0; i<30; i++) { var pos = Math.floor(Math.random()*100); pos = pos % paralen; charArray[pos].style.color = 'red'; } }); 
+3
source

You need to view the documentation for $. . Possible Solution:

 $('input').click(function() { var $para = $('#para'); var position = Math.floor(Math.random()*100); var character = []; for ( var i=0; i <= 30; i++ ) { character[i] = $("<span>" + $para.text().substr(position*(i+1), 1) + "</span>"); character[i].css('color', 'red'); } $para.empty(); $.each(character, function(idx, val) { $(val).appendTo($para); }); }); 
+2
source

Source: https://habr.com/ru/post/1469496/


All Articles