Creating a new attribute using jQuery

Possible duplicate:
jQuery.attr returns user attributes undefined

I have a strange problem, but I hope that I'm just doing something stupid. I am trying to create a new attribute of an <img> element using jQuery, and this line:

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

When I check the DOM in Chrome, I just see selected = "selected", regardless of what I set the value to.

Just additional information: I can’t use only logical values, since I need to track the values ​​of the Yes, No, and Partial properties. I call the JS function from the onClick event of img itself and pass this as a parameter. I checked the object in the method and passed the correct object; the fact that the attribute is set (even if the error value) also supports this.

I'm sure I am doing something stupid here ... Any advice would be appreciated.

+6
source share
4 answers

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

In jQuery, you process user data attributes using the .data() method.

Custom data attributes are described in the HTML5 specification here .

+11
source

you can insert the data-* attribute as such

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

your element will set the data-selected attribute

+5
source

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

+2
source

The DOM property is different from the DOM attribute;)

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

+1
source

Source: https://habr.com/ru/post/928004/


All Articles