Gravitational FX
Gravitational FX

Reputation: 33

How to place a <span> on 1st word within a H1 and href tag

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:

  1. Source = <h1>This is a test</h1>

    Output = <h1><span>This</span> is a test</h1>

  2. 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

Answers (4)

Waqar Alamgir
Waqar Alamgir

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(' '));
            }
        }
    });

Demo

Upvotes: 0

Yograj Gupta
Yograj Gupta

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

FluffyJack
FluffyJack

Reputation: 1732

Check out lettering.js you can have it wrap words and letters. Its awesome.

Upvotes: 0

NullPoiиteя
NullPoiиteя

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

Related Questions