John Christensen John Christensen - 29 days ago 8
jQuery Question

Loop through string and style individual letters

I have the title "INTRO TO GRID", and I want to individually style the letters in the string "GRID". I know I could do this with CSS, but I want to try with JS. I am having difficulty figuring out how to attach .css() to the individual letters. I have attached my code for reference. Thanks in advance!

var header = $("#header").text();

var grid = header.substring(9, header.length);

var chars = grid.split("");

for(var i = 0; i < chars.length; i++){
console.log(chars[i]);
}

console.log(chars);


With the help previous commenters, here is the solution to my problem.

var header = $("#header");

var chars = header.text().split("");

var headerSpans = chars.map(function(char){
return $('<span>' + char + '</span>');
});

$(header).html(headerSpans);

for(var i=9; i <= headerSpans.length; i++){
headerSpans[i].css({
"margin" : "20px",
"background-color" : "red"
});
}

Answer Source

@Jon Uleis is right, you cannot style individual characters. But you can style DOM elements, like <span>:

var header = $('#header'),
    headerSpans = header.text()
                        .split("")
                        .map(function(char){
                           return $('<span>' + char + '</span>');
                        });
header.html(headerSpans);

headerSpans[9].css('color', 'red');
headerSpans[10].css('color', 'blue');
headerSpans[11].css('color', 'green');
headerSpans[12].css('color', 'orange');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">INTRO TO GRID</div>