Reputation: 3352
Using javascript I'm looping through my H3 elements like this:
$('h3').each(function(){ });
I'm then generating an anchor for that tag formatted like this: "section-x" where x increments for each H3 on the page. The problem I have is that I'd like the first letter of the header to be an anchor link, like this:
*H*eading
.. where H is underlined, representing a link. I can format the anchors however I don't know how to wrap a hyperlink tag around the first letter in each heading. Some help would be greatly appreciated.
Regards, kvanberendonck
Upvotes: 3
Views: 363
Reputation: 35253
Let's throw some plain javascript into the mix:
$('h3').html(function(i){
var self = $(this)
, html = self.html()
return html[0].anchor('section-'+i) + html.substring(1)
})
html
(and most other setter functions) accepts a function as an argument and uses the return value for each element"string".link(target)
creates the code <a href="#target">string</a>
. A nice vintage useful methodedit: switched from .link
to .anchor
. Anchors are deprecated though, you should start using IDs for that:
$('h3').html(function(i){
var self = $(this)
, text = self.text()
// give the H3 an id and link to it
// ideally the headers should already have an id
this.id = 'section-'+i
return text[0].link('#section-'+i) + text.substring(1)
})
Upvotes: 2
Reputation: 3491
Something like this?
$('h3').each(function(){
var currentHeading = $(this).text();
$(this).html("<a href='link'>" + currentHeading.substr(0,1) + "</a>" + currentHeading.substr(1, currentHeading.length - 1));
});
Upvotes: 5
Reputation: 60584
$('h3').each(function(i){
var firstLetter = $(this).text()[0];
$(this).html('<a href="where.html">' + firstLetter + '</a>' + $(this).text().substr(1));
});
Not sure where you'd like to put section-x
in that heading, but you can use i
inside that each()
to get the current iteration index.
Upvotes: 1