Search code examples
javascriptjquerywordpresshref

How can I add a class to an anchor in a list item?


I am building a website in Wordpress and need to add a class to the anchor element that is inside a list item. The list item has a unique ID. The class I need to add will give me smooth scrolling on the anchor link.

I do not want to alter the theme, that is why I want to add a class with JavaScript, or any better technique.

This is what I have tried but does not work:

$('li#menu-item-318').find('a').addClass('fl-scroll-link');

I my Console I get this error:

TypeError: $ is not a function. (In '$("#menu-item-318 a")', '$' is undefined) Error: {}

This is the specific code on my website:

<nav class="top-bar-nav"><ul id="menu-topbalk"><li id="menu-item-318"><a href="#contactgegevens" class="nav-link">Contact</a></li></ul></nav>

So the above a tag needs to get this second class: fl-scroll-link so that this will be the result:

<a href="#contactgegevens" class="nav-link fl-scroll-link">Contact</a>

I am learning every day and could use your help. Please explain the solution you propose.

// Solution //

Thanks a lot everyone, together we made it work! Hooray!

So I made 2 mistakes:

  1. I was looking for a class but of course should be looking for an id.
  2. Wordpress is uses jQuery instead of $!

The working code is:

jQuery(document).ready(function($) {
    $("#menu-item-318 a").addClass("fl-scroll-link");
});

Thanks again, I am very happy!


Solution

  • There is a missing closure on your list item (or was)

    <nav class="top-bar-nav">
      <ul id="menu-topbalk">
        <li id="menu-item-318">  <!-- missing ">" here -->
          <a href="#contactgegevens" class="nav-link">Contact</a>
        </li>
      </ul>
    </nav>
    

    To add the fl-scroll-link class to an anchor use the .addClass() method. Apply this to all of the child <a> elements underneath the menu like below. Since you're already using jquery I've used that also.

    jQuery(document).ready(function($) {
        $("#menu-item-318 a").addClass("fl-scroll-link");
    });
    

    Also if you wanted to actually access it by its anchor href value there is another question that has answered that already here: How to get an element by its href in jquery?

    In your case:

    jQuery(document).ready(function($) {
        $('a[href="#contactgegevens"]').addClass("fl-scroll-link");
    });
    

    The error message about "$" being undefined means that your jquery library isn't being loaded. You'll want to make sure that your custom javascript is added AFTER the site loads jquery... or below is a pure javascript way to add a class to that <a> tag.

    document.querySelector('a[href="#contactgegevens"]').classList.add("fl-scroll-link");
    

    or if you wanted to apply that class to all <a> tags under the list item.

    document.querySelector('#menu-item-318 a').classList.add("fl-scroll-link");