views:

16257

answers:

3

i am use $(expr).attr("hash",value) to set a "hash" attribute for HTML anchor element "a" but the Jquery would not do that. but if i change expr to "div", then i can set "hash" attribute to "div" tag.

is this behavior a xhtml specification? i can set "id" of "a" tag attribute. since id is a built in attribute for html "a" tag.

+5  A: 

Probably your trouble is that there isn't any hash attribute for an <a> tag. Perhaps you're looking for the name attribute, or maybe you want to change the hash in the link href, in which case you'll have to parse the link text and replace the hash using regular expressions.

Ben Alpert
+5  A: 

to set a "hash" attribute for HTML anchor element "a"

The <a> element (HTMLLinkElement) already has a DOM Level 0 hash property. It is used like window.location.hash to read or set the ‘...#anchor’ part at the end of the URL being referred to by the element's href.

Setting a.hash, whether directly or through jQuery's attr() wrapper, merely sets the anchor name in the link's URL. You could deliberately say you want an actual attribute by calling the DOM method a.setAttribute('hash', value), except that this doesn't work in IE6/7 due to a long-standing bug where it confuses attributes and properties.

This is one of the problems with adding custom non-standard attributes to elements, you never know when it's going to clash with an existing name. HTML5 will suggest you limit your custom attributes to names starting with ‘data-’, but in general it's best to find another way of storing data if you can.

bobince
A: 

Another option for setting the hash. this only works where the expression returns an a element. This is because hash is a property on the actual a dom element.

$(expr).each(function() {
  this.hash = value;
});

if your need to test to see whether its an a tag use this

$(expr).is('a').each(function() {
  this.hash = value;
});

in the case where you actually want to append some custom attribute I would recommend adding the value using the data method

$(expr).data('myHash', value);
bendewey