0

I want to add css class to links (using Javascript) that match begining of link. My links are currently looking like that:

http://localhost/MainApp/User/UserEdit.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1

And I want to check out only the part before id: /MainApp/User/UserEdit.aspx

I already have function that is adding css class to links and it looks like that:

function markActiveLink() {    
        var path = location.pathname;
        var home = "/";
        $("a[href='" + [path || home] + "']").parents("li").each(function () {
            $(this).addClass("selected");
        });
    }

value of location.pathname is /MainApp/User/UserEdit.aspx

Question: How can I modify my function markActiveLink() so that it will mark links even with id after main part of link?

Any help here much appreciated!

2 Answers 2

3

Use starts with selector instead of exact selector for href attribute.

Change:

 $("a[href='" + [path || home] + "']")

to

 $("a[href^='" + [path || home] + "']")

To address issue with the home path selecting all the links change the makeActiveLink to as follows:

function markActiveLink() {             
    var path = location.pathname;         
    var links = null;
    if(path){
        links = $("a[href^='" + path  + "']");
    } else {
        links = $("a[href='/']");
    }
    links.parents("li").each(function () {             
        $(this).addClass("selected");         
    });     
} 
Sign up to request clarification or add additional context in comments.

Comments

0

Not that it is the best solution, but you could use the contains selector:

$("a[href*='" + [path || home] + "']")

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.