Jump to content

Need help with Jquery each function [SOLVED]

crispybagel

Hi, I'm trying to create a function that navigation links for each new post that is made to a website that i'm creating. I'm having trouble applying the correct href as well as a name to each individual navigation link. 

 

This is a short-hand version of the HTML used.

<div class="post-container" id="001">
 <table class="post-title">
  <tr>
   <th>POST 001: Name</th>
  </tr>
 </table>
</div>
<div class="post-container" id="002">
 <table class="post-title">
  <tr>
   <th>POST 002: Name</th>
  </tr>
 </table>
</div>

and the Jquery function

function postchecker(){
    post = $(".post-container");
    $(post).each(function(){
      id = "#" + $(this).attr("id");
      name = $(this).find(".post-title th").text();
      $(".nav-post-wrapper").append('<a class="nav-link" href=""><span></span></a>');
      >> Apply the variable "id" as href to the appended element .nav-post-wrapper 
      >> Insert the variable "name" into the span inside the .nav-post-wrapper
    });
  };

How exactly would i go about applying the id and name as described in the code? Can i insert variables directly in to the append() somehow?

The appended elements should look like this in the HTML.

<a class="nav-link" href="#001"><span>Post 001: Name</span></a>
<a class="nav-link" href="#002"><span>Post 002: Name</span></a>
etc.


EDIT: managed to find a solution, set the append as a variable with id and name like this.

function postchecker(){
    post = $(".post-container");
    $(post).each(function(){
      id = "#" + $(this).attr("id");
      name = $(this).find(".post-title th").text();
      navlink = '<a class="nav-link" href="'+id+'"><span>'+name+'</span></a>'
      $(".nav-post-wrapper").append(navlink);
    });
  };
Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×