John Christensen John Christensen - 6 months ago 29
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++){


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

var header = $("#header");

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

var headerSpans ={
return $('<span>' + char + '</span>');


for(var i=9; i <= headerSpans.length; i++){
"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()
                           return $('<span>' + char + '</span>');

headerSpans[9].css('color', 'red');
headerSpans[10].css('color', 'blue');
headerSpans[11].css('color', 'green');
headerSpans[12].css('color', 'orange');
<script src=""></script>
<div id="header">INTRO TO GRID</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download