-3

I want to change the hyperlink colour property in CSS by using jQuery .toggleClass. Here is what I mean:

The CSS class with [a] (hyperlink) in which I want to change the colour

.navigation a { color: black;}

The colour I want to change to:

.color-change-to-white-text {
   color: white;}

jQuery I wrote, but it does not work:

$('a.navigation').toggleClass("color-change-to-white-text");

Is there any way to do this kind of styling?

  • 1
    `a.navigation` is the wrong selector - `.navigation a`!! – Paulie_D Mar 23 '21 at 20:14
  • Your css is `.navigation a` but your selector is `a.navigation` - these are not the same thing. If you include the HTML we can tell you which is correct. – freedomn-m Mar 23 '21 at 20:31
  • 1
    Does this answer your question? [What is the order of precedence for CSS?](https://stackoverflow.com/questions/25105736/what-is-the-order-of-precedence-for-css) – freedomn-m Mar 23 '21 at 20:39
  • Your issue is css precedence. `.navigation a` takes precedence of `.white` so will always use those styles, regardless of whether you add the class using jquery or directly. See here https://jsfiddle.net/76jh3edg/ for an example and the linked answer for more details. – freedomn-m Mar 23 '21 at 20:41
  • You are all right friends. I have done this the way I have wrote it above, as `.navigation a` wasn't working for me either, doesn't know why. – georgyhere Mar 23 '21 at 21:17

1 Answers1

0

.toggleclass doesn't change classes: it toggles them, so if you want to change an element's class, you could use the jQuery $(/* id */).attr("class", "color-change-to-white-text"). If you prefer pure Javascript, you can use document.getElementById(/* id */).setAttribute("class", "color-change-to-white-text").

  • `.toggleClass` is fine here - otherwise it would be `.addClass` - you would very unlikely want to use `.attr("class"` in jquery. OPs issue is with the selector they are using, not how they are changing the class. – freedomn-m Mar 23 '21 at 20:33
  • Correction, OPs issue is *also* caused by css precedence (and the selector is wrong...) – freedomn-m Mar 23 '21 at 20:41
  • I have used the `.toggleClass` as I want to change the colours back and fourth. It is easier (I could be wrong here) that way. – georgyhere Mar 23 '21 at 21:19