cyclone200
cyclone200

Reputation: 387

Get H3 and build link with ID

I'm trying to get all the H3 elements on my page to build links and create a dynamic summary.

So here's what I have :

$('h3').attr('id', function() {
    return this.innerHTML;
});

$('h3:not(:last)').append(" › ");
var headers = $('h3').text();

$('.summary').append(headers);

I have this : Header1 › Header2 › Header3 › Header4

But I don't know how to use the ID of each H3 elements and build links like to have something like this :

<a href="Header1">Header1</a> › ...

Thank you for your help.

Regards.

EDIT : Another problem is that the " › " is also added in my H3 and not only in the summary...

Upvotes: 0

Views: 320

Answers (2)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

try this ...loop throught all h3 using .each()

$('h3').each(function(){
   var getId = $(this).attr('id');  // to get id for this h3
   var headers = $(this).text();  // to get text for this h3
   // to change this h3 html with anchor 
   $(this).html('<a href="'+headers +'">'+headers +'</a>  › '); 
});

this code will convert

<h3>Header1</h3>

to

<h3><a href="Header1">Header1</a> > </h3>

is that what you looking for??

and if you want to append anchors to .summery class .. just use

$('h3').each(function(){
       var getId = $(this).attr('id');  // to get id for this h3
       var headers = $(this).text();  // to get text for this h3
       // to change this h3 html with anchor 
       $('.summery').append('<a href="'+headers +'">'+headers +'</a>  › '); 
    });

result of this code

<div class="summery">
   <a href="Header1">Header1</a> > 
   <a href="Header2">Header2</a> > 
   <a href="Header3">Header3</a> > 
   ......
</div>

Upvotes: 1

Robbert van der Helm
Robbert van der Helm

Reputation: 36

You should use jQuery's .each() function, like this:

$(document).ready(function() {
  $('h3').each(function(index) {
    var id = $(this).attr('id');
    var text = $(this).text();

    var spacer = index ? ' > ' : ''; // Don't show a spacer for the first item
    var header = spacer + '<a href="#' + id + '">' + text + '</a>';

    $('.summary').append(header);
  });
});

Codepen

Upvotes: 1

Related Questions