jquery addclass styling doesn't work, wrong selector?

22,304

Solution 1

Saying

$("#leistungen").addClass("brown");

will work on all text inside #leistungen, but not on anchor tags. Anchors have a default style that must be overridden. You are correct in writing

$("#leistungen a").addClass("brown");

Do a test to make sure your Javascript is executing by changing it to

$("#leistungen a").hide();

If it disappears, then you know that your Javascript is working on the correct element. Next, try being more specific with your selector (maybe something else is overriding your change).

$("li#leistungen a").addClass("brown");

If that doesn't work, make sure the javascript has executed and then inspect the element. Does it have the new class? If so, then the problem is with the CSS rather than the Javascript. Check your CSS file surrounding the ".brown" style to look for syntax errors. A missing } from the previous style would do it.

Try using "#4C3F12" instead of the word "brown" as a colour.

.brown {
  color: #4C3F12;
}

Let me know if any of these help!

Solution 2

Case-sensitivity -- you named your anchor with an upper-case L.

$("#Leistungen").addClass("brown");

In the first case, also, you'd need to use a class selector, not an id selector

$(".leistungen a").addClass("brown");

Note -- I'd avoid classes and ids that match (with or without case sensitivity).

HTML ID Attribute docs (emphasis mine):

The ID attribute uniquely identifies an element within a document. No two elements can have the same ID value in a single document. The attribute's value must begin with a letter in the range A-Z or a-z and may be followed by letters (A-Za-z), digits (0-9), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). The value is case-sensitive.

Share:
22,304
user134282
Author by

user134282

Updated on September 19, 2020

Comments

  • user134282
    user134282 almost 4 years

    <li id="leistungen"><a href="#Leistungen" onclick="sitemapChangeSubMenu('leistungen','leistungencontent','leistungen'); return false;">LEISTUNGEN</a> </li>

    This is the list-item which I want to style with:

    $("#leistungen a").addClass("brown");
    

    This doesn't work for either:

    $("#leistungen").addClass("brown");
    

    my css code is just

    .brown {
       color:brown;
    }
    

    I don't know what is wrong, hopefully you can help me :)

    thanks a lot!