Why doesn't attr(attributeName, value) create a new Attr object in the DOM attributes NamedNodeMap?
-
08-10-2019 - |
Pergunta
I can change the value attribute of a HTMLOptionElement by doing so:
sizeOptionToBeSelected.attr('value', '555');
It changes the value property of the HTMLOptionElement and the value in the DOM Attr object in the NamedNodeMap attributes property from the same HTMLOptionElement object.
But, I cannot create a new Attr "selected" or change the selected property of the HTMLOptionElement with the following code:
sizeOptionToBeSelected.attr('selected', 'true');
Why do you think this is? How can I do this?
From jquery documentation:
We can add an attribute the same way: $('#greatphoto').attr('title', 'Photo by Kelly Clark');
Additional explanations:
- The code runs inside the $(document).ready( function so there is no problem with the loading.
- I use the latest Google Chrome 8.0.552.215 beta.
Kind Regards,
Despot
Solução
jQuery, somewhat confusingly, tends to treat attributes and properties as the same thing. So $(elem).attr('selected', true)
is actually setting elem
's selected
property to true, not its attribute.
There are very few reasons to need to set the selected
attribute. Setting the selected
(and defaultSelected
) properties should suffice.
Also, bear in mind that the selected
attribute corresponds to the default state, not the current state.