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
text(); alert(header);
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.
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)
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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With