Search code examples
javascriptjquerycallbackhrefmatching

jQuery detect if document contains an id matching the href of a link


I've written a function that adds hrefs to an alphabetical navigation bar. I made it so each letter section gives itself an ID. I want to make it so in the event there isn't for example a "C" section, I could add a class to the link linking to #c that would disable it. Here's what I have so far:

 <ul class="no-bullet inline">
      <li><a class="scroller"><strong>A</strong></a></li>
      <li><a class="scroller"><strong>B</strong></a></li>
      <li><a class="scroller"><strong>C</strong></a></li>
</ul>

  <div class="space-above space-below letter-section">
       <h4 class="alpha-heading"><strong>A</strong></h4>
        <ul class="no-bullet">
             <li><a class="naming" href="#">Benny Goodman</a></li>
             <li><a class="naming" href="#">Benny Goodman</a></li>
             <li><a class="naming" href="#">Benny Goodman</a></li>
         </ul>
   </div>
 <div class="space-above space-below letter-section">
       <h4 class="alpha-heading"><strong>A</strong></h4>
        <ul class="no-bullet">
             <li><a class="naming" href="#">Benny Goodman</a></li>
             <li><a class="naming" href="#">Benny Goodman</a></li>
             <li><a class="naming" href="#">Benny Goodman</a></li>
         </ul>
   </div>
 <script>
 function alphaLink() {
       var alphaLink = $(this);
       var alphaLinkRef = "#" + alphaLink.text().toLowerCase();
       $(alphaLink).attr("href", alphaLinkRef);
   };
   $('.scroller').each(alphaLink);

   //assigns each content section an ID

   function alphaID() {
       var section = $(this);
       var sectionID = section.text().toLowerCase();
       $(section).attr("ID", sectionID);
   };
   $('.alpha-heading').each(alphaID);

linkMatch function(){
   var link = $(this);
    if(link.length <= 0) {
    $(this).addclass("disabled");
}

$("scroller").each(linkMatch);
</script>

Solution

  • I took Jeremiah's code and altered it slightly to do what I needed it to do. Thanks so much for all the answers- here was the final product:

       function findID(ID) {
         var exists = false;
         if ($(ID).length > 0) {
          exists = true;
         }
         return exists;
     }
    
     function matchLink() {
         var href = $(this).attr('href');
         if (!findID(href)) {
             // Doesn't exist
             $(this).addClass('alpha-disabled');
         }
     };
     $('.scroller').each(matchLink);