tags:

views:

89

answers:

3

How to select parent object of a hyperlink whose href match the requested page/file name using jQuery?

I have following code

<div>
<div class="menu-head">
<a href="empdet.aspx">employees</a>
<a href="custdet.aspx">customers</a>
</div>
<div class="menu-head">
<a href="depdet.aspx">departments</a>
</div>
<div>

I want a Jquery to change the color of the parent div corresponding a hyperlink. If the user is browsing custdet.aspx the respective parent div background should be changed to red.

Edit: I have a method to retrieve the file name. I just need the right selector to select the parent.

+1  A: 
$(document).ready(function () {
    $('selector-to-get-your-nav a[href^=' + window.location.pathname + ']').parent().css('backgroundColor', '#FF0000');
});

window.location.pathname will prefix the path with a /, so either add a slash to the beginning of your URLs, do window.location.pathname.slice(1), or change the selector from href^= to href~= to do a CONTAINS search rather than an equals (or change any of the other selectors instead.

Edit: There is no selector to get the parent. You select the child, then use .parent()

Matt
It could be more than a `/`. I was going to suggest something similar using `document.location.pathname.slice(document.location.pathname.lastIndexOf('/')+1)` instead of `window.location.pathname`
drs9222
i have used following code to find the path. var sPath = window.location.pathname;var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
ARS
@drs9222: Sorry.. I assumed his links were absolute. It depends how he fancies doing his links. If he was to have a link as `foo/bar/index.html`, then your example wouldn't work... swings and roundabouts :)
Matt
A: 
$('#menu-head a').each(function() {
  if (window.location.pathname.indexOf($(this).attr('href')) > -1) $(this).parent().addClass('myRedClass');
});
mamoo
+1  A: 

I tried to post this over 2 hours ago and my internet died. It just came back on so I'll add it to the list.

You can get the current path using document.location.pathname, to get the filename from the end split() on "/" and pop() the resulting array:

// get the current filename
var file = document.location.pathname.split("/").pop();

// get the parent of a matching hyperlink
var lPar = $('#menu-head > a[href="'+file+'"]').parent();

Side note: in your example you have two div elements with the same id (menu-head). Duplicate IDs are invalid on the same page and you will run into issues if you do not make them unique.

Andy E
This is what is was looking for. Thanks a lot Andy :)
ARS