outerHTML and attribute updates
-
26-12-2019 - |
Question
I'm trying to get the HTML code as a string with the attribute updates.
I've a select
tag, whose options I update using JavaScript.
By default, a first option
is selected
using the HTML attribute selected="selected"
.
If I unset selected
from the first option using option1.selected = false
and set option2.selected = true
for the second option
, and then call the outerHTML
of a select
, I get
<select>
<option selected="selected">one</option>
<option>two</option>
<option>three</option>
</select>
As you can see, selected
attribute is still on the first option
, while it has been moved to the second option
. The expected result is
<select>
<option>one</option>
<option selected="selected">two</option>
<option>three</option>
</select>
Here's an example http://jsbin.com/adAbAMe/2/edit?html,js,console,output (click run with js
to get a result) which shows, that if a selected
attribute has been changed, it doesn't change in the HTML code.
But I need to get the final HTML from outerHTML with the successful attribute updates, because if I move this select
somewhere I won't get any updates I've made before using JavaScript.
Is there any method to get the HTML as a string with the real attributes values?
Solution
The selected
attribute isn't automatically updated, but you can set it to be removed and added to the proper elements.
//remove "selected" from first
if (i==0) {
option.selected = false;
option.removeAttribute("selected");
}
//add "selected" to second
if (i==1) {
option.selected = true;
option.setAttribute("selected", "selected");
}
OTHER TIPS
You can use
option.setAttribute('selected', 'selected');
and
option.removeAttribute('selected');
Try
$('button').click(function () {
console.log($('select').prop('outerHTML'))
})
$('select').change(function(){
$(this).find('option[selected]').removeAttr('selected');
$(this).find('option:selected').attr('selected', 'selected');
})
Demo: Fiddle
From the DOM Specification:
selected of type boolean
Represents the current state of the corresponding form control, in an interactive user agent. Changing this attribute changes the state of the form control, but does not change the value of the HTML selected attribute of the element.
(emphasis mine)
To get the effect you're looking for, you want option.setAttribute('selected', 'selected')
, though you'll also need option.removeAtrribute('selected')
on the other options.