caramba caramba - 29 days ago 7
Javascript Question

Is selected option selected if attribute is in DOM or not

To create a Dual Listbox like Bootstraps I needed to remove the default gray color of

selected
option. The only way to remove this gray color was to change the selected state of the element to false. No other trick worked to remove the gray background color of selected option.

Now if I do so, the attribute
selected
still remains in DOM but seems to be false. I thought if we have an element like:

<option value="1" selected>1: Lorem ipsum</option>


if
selected
is there it means always option selected true as it is the same as:

<option value="1" selected="selected">1: Lorem ipsum</option>


or

<option value="1" selected="true">1: Lorem ipsum</option>


but this seems not to be like so. Could anyone shed some light on this for me?

I've created a fiddle https://jsfiddle.net/npm6tn0m/ trying to demonstrate the scenario. Where the css

option[selected] {
background-color: orange;
}


only works for the
selected
option which is set to false but still has the
selected
attribute in DOM. Cause this may vary across different browsers here is an image from what I see in OSX Chrome browser:

enter image description here

All code like in the fiddle also here on SO:



var elements = document.querySelectorAll('.special option');
for(var i=0; i < elements.length; i++) {
elements[i].selected = false;
}

setTimeout(function(){
var elements = document.querySelectorAll('option');
for(var i=0; i < elements.length; i++) {
console.log('Value = ' + elements[i].value + ' selected: '+ elements[i].selected);
}
}, 1000);

option[selected] {
background-color: orange;
}

<select class="special" multiple>
<option value="1" selected>1: Lorem ipsum</option>
<option value="2" >2: dolor sit amet</option>
</select>

<select multiple>
<option value="3" selected>3: Lorem ipsum</option>
<option value="4" >4: dolor sit amet</option>
</select>




Answer

I thought if we have an element like:

<option value="1" selected>1: Lorem ipsum</option>

if selected is there it means always option selected true as it is the same as:

<option value="1" selected="selected">1: Lorem ipsum</option>

...

but this seems not to be like so. Could anyone shed some light on this for me?

You're correct about how boolean attributes work, just not about what the selected boolean attribute represents. :-)

The selected attribute represents the default selected state, not the current selected state. It's like an input's value attribute in that way; the default (used in case of form reset, for instance), not the current value.

Just as the current value of an inputis not represented in the DOM, similarly the current value of a option's selectedness is not represented in the DOM.