Jquery href value problem

I have a link and i am putting the id in href.

<a href="12345" id="myLink">link</a>

In IE 8.0.6 and 6.5 (not my machine but on coworkers machine) when link gets clicked, i get full path including the ID like “http://www.domina.com/folder/12345” where as on my machine i get the ID only when i do

myval = $("#myLink").attr("href");

When i move the ID to rel attribute, the browsers behave as intended.

myval = $("#myLink").attr("rel");

I am confused now, same version of IE on my machine is behaving ok where as on coworkers machine it is not. Am i doing some thing wrong here?

Try to return false, that should do it.


$("#myLink").click(function () {
  var id = $(this).attr('href');
  alert(id);

  return false;
});

But remember if someone has their JS disabled they will be directed to url.com/id_here. I would suggest placing the ID somewhere else and leaving the href as href=“#”

Some versions of IE normalize the HREF attribute (making it an absolute URL).

You could simply remove everything up to and including the last slash, e.g.


myval = $("#myLink").attr("href").replace(/.+\\//, '');

YBH305: false is in there. This is internal site and all users know to have js enabled.

JimmyP: I checked this on the same IE version but different machines. Like i said mine worked where as the coworkers didn’t. Thanks for the replace, i am currently using rel and it is working in all the browsers for me.

You can fix this by taking a different approach if you require the to have unique IDs


<a href="#" class="myLink" id="12345">link</a>

$(".myLink").click(function (event) {
  var id = $(this).attr("id");
  alert(id);

  return false; //or event.preventDefault();
});

The href attribute is for putting an actual url, or a reference to a fragment identifer (which can be resolved to a url).

You have experienced problems due to your wanting to use the href attribute for what is not its intended purpose.

As a side-note, to cater for browser differences, you can get the fragment identifier from an href by using href.split(‘#’)[1]

YBH305: thanks for the alternate approach, css selectors make life so easy withj jQuery.