JQuery, set attribute for tag

I use $ (expr) .attr ("hash", value) to set the "hash" attribute for the HTML anchor element "a" but JQuery does not. but if I change expr to div, then I can set the hash attribute for the div tag.

is this xhtml behavior? I can set the "id" of the tag attribute "a". since id is a built-in attribute for the html "a" tag.

+7
jquery attributes
source share
3 answers

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

The <a> (HTMLLinkElement) element already has the DOM Level 0 hash property. It is used as window.location.hash to read or set the "... # anchor part at the end of the URL that the href element refers to.

Configuring a.hash , whether directly or through jQuery attr() wrapper, simply sets the binding name in the url. You could consciously say that you want to get the actual attribute by calling the DOM method a.setAttribute('hash', value) , except that this does not work in IE6 / 7 due to a long-standing error in which it mixes the attributes and properties.

This is one of the problems with adding custom non-standard attributes to elements; you never know when they will encounter an existing name. HTML5 will offer you to limit your user attributes to names starting with "data-", but in general, it's best to find another way to store data if you can.

+13
source share

Probably your problem is that there is no hash attribute for the <a> tag. You may be looking for the name attribute, or perhaps want to change the hash in the href link, in which case you will have to parse the link text and replace the hash with regular expressions.

+6
source share

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

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

if you need to check if this tag uses this

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

in case you really want to add some custom attribute, I would recommend adding a value using the data method

 $(expr).data('myHash', value); 
0
source share

All Articles