Reputation: 979
CSS (currently) does not have any sort of nth-letter
psuedo-selector. Is there a way to mimic this selector with jQuery, without using a bunch of span
tags?
Any help greatly appreciated!
Upvotes: 4
Views: 2181
Reputation: 12730
It's not possible to use jQuery to pull out a specific letter because jQuery is a query language to pull out DOM elements. You would need to split the text nodes and create new DOM elements (such as with a span) to actually target the specific letter. However, it's not possible "without a bunch of spans."
Here's my attempt at something similar. I should say that I don't really consider this production quality and it will totally have some bugs associated with it. I hope it can instead give you some idea how to approach this problem using primarily string manipulation.
Again, this is a quick and dirty example to get you started.
function colorizeNthLetter(text, letter) {
var words = text.split(' ');
for (var i = 0; i < words.length; i++) {
if (words[i].length > letter) {
words[i] = words[i].substring(0, letter-1) +
"<span class='color'>" +
words[i].substring(letter-1, letter) +
"</span>" +
words[i].substring(letter);
}
}
return words.join(" ");
}
One likely bug is that splitting on a space to determine words is likely an incomplete way of thinking about word separation. There's going to be more. :)
Upvotes: 1
Reputation: 3348
Unless your letter is wrap in a tag of sort (span, em, div, or whichever...), it is not a DOM element. So you can not in effect target it directly with CSS or DOM-manipulation functions.
Upvotes: 2