Reputation: 33
I'm trying to insert a span around the first word in an H1 tag.
Unfortunately the tags can also be links and can include classes etc, eg:
Source = <h1>This is a test</h1>
Output = <h1><span>This</span> is a test</h1>
Source = <h1 class="blah blah"><a href="#">This is a test<a/></h1>
Output = <h1 class="blah blah"><a href="#"><span>This</span> is a test<a/></h1>
Has anyone done this before in say jQuery?
Upvotes: 3
Views: 355
Reputation: 9978
Works for both "a" tag in it and plain text.
$('h1').each(function(){
if($(this).find('a').length>0)
{
var text = $(this).find('a').html();
text = text.split(' ');
if(text.length>0)
{
text[0] = '<span>' + text[0] + '</span>';
$(this).find('a').html(text.join(' '));
}
}
else
{
var text = $(this).html();
text = text.split(' ');
if(text.length>0)
{
text[0] = '<span>' + text[0] + '</span>';
$(this).html(text.join(' '));
}
}
});
Upvotes: 0
Reputation: 9869
You can try this, It will work for both example.
$('h1').each(function(){
var self = $(this);
var p = self.text().split(' ');
var html = self.html().replace(p[0], '<span>'+ p[0] +'</span>');
self.html(html);
});
Check this Demo
Upvotes: 0
Reputation: 1732
Check out lettering.js you can have it wrap words and letters. Its awesome.
Upvotes: 0
Reputation: 57322
this can be done by
$(' your selecter').each(function(){
var one = $(this);
one.html(one.html().replace(/^(\w+)/, '<span>data</span>'));
});
Upvotes: 1