0

URL example: www.example.com/services/#service1

My various category elements each have a certain ID, the one I'm locating is #service1. I want to make that category active by adding "active-category" class to it. This is my code.

var hash = window.location.hash;
$(hash).addClass("active-category");

when I do: alert(hash); I can see #service1

When I input it into $(hash).addClass('active-category');

The class isn't added to the element when I check in the console.

Peter Krebs
  • 3,831
  • 2
  • 15
  • 29
  • If `hash` really contains `#service1`, that code **will** add a class to the first `id="service1"` element in the DOM. Perhaps you have more than one and you're looking at one of the later ones? – T.J. Crowder Aug 04 '21 at 08:19
  • See also (probably a dupetarget, actually): http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – T.J. Crowder Aug 04 '21 at 08:20
  • 2
    Note: Please use `example.com` for placeholder domains. That's what it's for. There actually is a `website.com` and so I thought at first you were pointing us at a page with the problem DOM and code. – T.J. Crowder Aug 04 '21 at 08:22
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – freedomn-m Aug 04 '21 at 08:33
  • 1
    @T.J.Crowder Thanks, i figured it out the other day. You were correct it should be working correctly, I just had my jquery code placed in the wrong area. Doh! Thanks for the tip on example.com, i'll use that next time. – Kanister21 Aug 07 '21 at 06:14

0 Answers0