How to insert an HTML tag around the first letter of a specific tag using jQuery?

I can not understand this. Is there a way to insert an HTML tag around the first letter of a specific tag using jQuery?

eg. I have it:

<h1>Heading</h1>

but I need it:

<h1><span>H</span>eading</h1>

I want to create a CSS animation in the first letter of a tag when I hover over it.

CSS h1:hover:first-letteris not supported at all. Targeting it with help <span>seems like my best bet. Unfortunately, pasting <span>directly into HTML is not an option.

Thank,

Matt

+5
source share
2 answers
var t = $('h1').text();
$('h1').html('<span>'+t.substring(0,1)+'</span>'+t.substring(1));

EDIT: , ( , ).

$('#main-nav li').each(function() {
    wrap_first_character(this, $('<span>'));
});

function wrap_first_character(ele, tag) {
    var t = $(ele).text();
    $(ele).append(tag.html(t.substring(0,1))).append(t.substring(1));
}
+5

, <h1> ( ), CSS <h1>. , :

JS

$('h1').wrap('<div>');​

CSS

div:hover h1:first-letter { color: red; }​

http://jsfiddle.net/HPYgX/

+3

All Articles