First letter of each <h3> into a hyperlink

Using javascript . I view my H3 items like this:

$('h3').each(function(){ });

      

Then I create an anchor for this tag, formatted like this: "section-x", where x is incremented for every H3 on the page. The problem is, I want the first letter of the title to be the anchor link, for example:

* H * eading

.. where H is underlined, representing a link. I can format the anchors, but I don’t know how to wrap the hyperlink tag around the first letter in each header. Some help would be greatly appreciated.

Regards, kvanberendonck

+3


source to share


3 answers


Add some simple javascript to 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) takes a function as an argument and uses the return value for each element
  • "string".link(target)

    generates code <a href="#target">string</a>

    . Good old useful method.


edit: switched from .link

to .anchor

. Anchors are not recommended, but you must use an ID for this:

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

      

+2


source


Something like that?



$('h3').each(function(){ 
    var currentHeading = $(this).text();

    $(this).html("<a href='link'>" + currentHeading.substr(0,1) + "</a>" + currentHeading.substr(1, currentHeading.length - 1));
});

      

+5


source


$('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 want to put section-x

in this header, but you can use i

internally each()

to get the current index of the iteration.

+1


source







All Articles