this is a part of my html file:
<form id="foo">
<select>
<option value="1" selected>1</option>
<option value="2">2</option>
</select>
</form>
Now when I use the following javascript code, it gives me the exact content of the form:
alert(getElementById("foo").innerHTML);
However, after I change my options withing the form, the above code still returns the previous version of the form's content.
For instance, let's say I've switch my option from "1" to "2". In this case I expect the above javascript code returns the form's content with option "2" selected; but no matter how I change the form, it always return the original version of the form's content.
People can struggle and complain about innerHTML not working. Such things usually occur because of human error, when strings are not appropriately defined, or there are some mistakes in JavaScript code.
To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.
Reading innerHTML causes the user agent to serialize the HTML or XML fragment comprised of the element's descendants. The resulting string is returned.
Content attributes show the initial state.
IDL attributes (aka properties) show the current state.
For example, let's say we have a text input like this:
<input value="foo" />
It's default text is "foo". Let's change it to "bar". Then,
input.getAttribute('value')
will be the initial value: "foo"
.input.defaultValue
will be equivalent to the above: "foo"
.input.value
will be the current value: "bar
.var inp = document.querySelector('input');
(inp.oninput = function() {
document.getElementById('attr').textContent = inp.getAttribute('value');
document.getElementById('defVal').textContent = inp.defaultValue;
document.getElementById('val').textContent = inp.value;
})();
<input value="foo" />
<p>Attribute: <span id="attr"></span></p>
<p>Default value: <span id="defVal"></span></p>
<p>Value: <span id="val"></span></p>
In your case it happens something similar. innerHTML
only shows the HTML markup, which includes content attributes (which reflect the initial state) but not IDL attributes (current state).
If you want the current state, read it with IDL attributes instead of using innerHTML
.
This is snippet from the Mozilla Developer Network page for innerHTML
.
More details here: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
This property was initially implemented by web browsers, then specified by the WHATWG and W3C in HTML5. Old implementations may not all implement it exactly the same way. For example, when text is entered into a text input, Internet Explorer changes the value attribute of the input's innerHTML property but Gecko browsers do not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With