0

I am trying to get the following bit of code to work, but I seem to be missing something

var dom = document.URL;
$("a[href=dom]").addClass("active");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>
    <a href="http://example.com">
        <i class="fa fa-home"></i>
        Home
    </a>
</li>
<li>
    <a href="http://example.com/about">
        <i class="fa fa-info"></i>
        About
    </a>
</li>

What's supposed to happen is when at http://example.com the class active will be added to the first a element, if at http://example.com/about then the second a will get the class.

I used javascript's alert to make sure I was getting the right URL, and it is as it shows in href, however what I have above doesn't work. I have tried the Javascript responses given here but they don't work either.

4
  • 2
    You just need to concatenate the variable: $('a[href="' + dom + '"]').addClass("active"); Commented Feb 24, 2016 at 17:00
  • you need to use window.location.href instead, and remove the class from all of those anchors prior to setting the class, otherwise they'll all have it Commented Feb 24, 2016 at 17:01
  • Not sure why this was downvoted. Seemed like a well put together question to me especially from a newer stack overflow member. Commented Feb 24, 2016 at 17:05
  • Thanks Rory, worked like a charm :) Commented Feb 24, 2016 at 17:07

1 Answer 1

1
$("a[href=dom]").addClass("active");

should be

$("a[href=" + dom + "]").addClass("active");

You're mixing in a variable with a string. Also, I would recommend just adding a class to the body and targeting the current page like that. It's much more reusable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.