Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


basic query question

hi guys. I need help to solve this, in jQuery.

I have a heading h1 , somewhere far away down on the same page i have four h2

I want to copy the text of the four h2 and put them like a list of links below the h1 and each link will send you to the part of the page were the correspondent h2 is.

the question: the each function run 4 times(once for each h2) somehow I want to change the name attribute of the anchor every time the each function runs and load this name to a variable, and then just use the variable to get the running anchor name attribute.

I know this can be done in a lot of different ways but i want to try this one.

$(document).ready(function() {
  $("h2").each(function() {

var sss= $(this).html();
$(this).append("<a name='+bbb+'></a>");

var bbb = // i don't know what to put in here

$("h1").append('<ul><li><a href="#'+bbb+'">'+sss+'</a></li></ul>'); 


1 Answer

Hey, here's my approach:

 $(document).ready(function() {
  var headers = $("h2"), 
      headersLength = headers.length;

  function appendLink(i, linkText){
    $("h1").append('<ul><li><a href="#' + 'section' + i +'">'+linkText+'</a></li></ul>'); 
     $('h2:eq(' + i + ')').attr('id', 'section' + i);

  for (i=0; i <= headersLength; i++){
    if ( i == 0) {
      appendLink(i, 'Link1 Custom text')
    } else if ( i == 1) {
      appendLink(i 'Link2 Custom text')
    } else if ( i == 2 ) {
      appendLink(i, 'Link3 Custom text')
    } else if (i == 3) {
      appendLink(i, 'Link4 Custom text')

check out the pen http://codepen.io/jxtposed/pen/WbORVa

hope this helps Ali M

Hi mate thx for your code, I learn about jquery: attr and length. However the solution was very simple , I just created a random string every time the each function run :

$(document).ready(function() {
  $("h2").each(function() {
     var sss= $(this).html();
     var randomString = Math.random().toString(36).replace(/[^a-z]+/g, '') 
     $(this).append('<a name="'+randomString+'"></a>');                  
     $(".content h1").append('<ul><li><a href="#'+randomString+'">'+sss+'</a></li></ul>');