0

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!

  • Tip: hit `f12` to see the developer console. Then, you can learn more about *why* things don't work, and then either figure it out on your own or post the reason here. It's called *attaching the stack/error trace* – Yarin_007 May 23 '22 at 18:26
  • `I have also learned that it is good to use classList:` there is nothing wrong with using `addClass` if you already use jQuery. The question is more if it makes sense to use jQuery at all nowadays. – t.niese May 23 '22 at 18:29
  • @Yarin_007 Thanks! I am working on an iPad and have an app installed called Inspect, so I have a Console and see all element. I checked the Console and what do you know, I got an error: `TypeError: $ is not a function. (In '$('li#menu-item-318')', '$' is undefined) Error: {}`. I have to research more to find out what it means. – koenmeteenk May 23 '22 at 18:48
  • I believe that WordPress uses `jQuery` instead of `$`. See https://stackoverflow.com/questions/12258282/typeerror-is-not-a-function-wordpress – j08691 May 23 '22 at 19:11
  • @j08691 Yesssss, that is it! It works! This works: `jQuery(document).ready(function($) { $("#menu-item-318 a").addClass("fl-scroll-link"); });` – koenmeteenk May 23 '22 at 19:30