6

Possible Duplicate:
jQuery .attr retrieving custom attribute returns undefined

I've got a weird problem, but I'm hoping I'm just doing something stupid. I'm trying to create a new attribute on an <img> element using jQuery, and this line:

$(selector).attr('selected', 'no');

When I inspect the DOM in Chrome, I just see selected="selected", no matter what I set the value to.

Just some extra info: I can't use just boolean values, as I need to keep track of "Yes", "No" and "Partial" property values. I'm calling a JS function from the "onClick" event of the img itself, and passing this as a parameter. I've inspected the object in the method, and the right object is passed; the fact that the attribute is set (even if to the wrong value) also supports this.

I'm dead certain I'm doing something stupid here... Any advice would be appreciated.

Community
  • 1
  • 1
ThinusP
  • 155
  • 1
  • 2
  • 7

4 Answers4

11

Selected is already an attribute in the HTML standard, so you cannot create a custom attribute with the same name. In that case, you should use the data- attributes instead and create an attribute data-selected for instance.

In jQuery you handle the custom data attributes using the .data() method.

The custom data attributes are described in the HTML5 spec here.

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
5

you could insert a data-* custom attribute like so

$(selector).data('selected', 'no');

your element will set a data-selected attribute

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
2

If you need to attach arbitrary data to an element, use .data(), not .attr().

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

A DOM property is different than a DOM attribute ;)

I'd suggest using $(selector).data() for your use case.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116