Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a HTML tag around the first letter of a specific tag with JQuery?

I can't figure this one out. Is there a way to insert a HTML tag around the first letter of a specific tag with JQuery?

e.g. I have this:

<h1>Heading</h1>

but I need this:

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

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

The h1:hover:first-letter CSS doesn't seem at all supported. Targeting it with the <span> seems my best option. Sadly inserting the <span> directly into the HTML is not an option.

Thanks,

Matt

like image 257
Matthew Blewitt Avatar asked Sep 05 '12 23:09

Matthew Blewitt


People also ask

How do I get the first letter of a word in jQuery?

text(); alert(header);

How to append at the beginning in jQuery?

jQuery prepend() MethodThe prepend() method inserts specified content at the beginning of the selected elements. Tip: To insert content at the end of the selected elements, use the append() method.

What is insertAfter in jQuery?

The insertAfter() is an inbuilt method in jQuery which is used to insert some HTML content after a specified element. The HTML content will be inserted after each occurrence of the specified element. Syntax: $(content).insertAfter(target)

What does prepend() do?

prepend() method inserts a set of Node objects or string objects before the first child of the Element . String objects are inserted as equivalent Text nodes.


1 Answers

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

EDIT: per your comment, break the code into a function and apply it to each element (I also made the function more dynamic so you can wrap the first character in anything you want).

$('#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));
}
like image 53
hackattack Avatar answered Sep 24 '22 17:09

hackattack