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?
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");
}