Jellicle
Jellicle

Reputation: 30206

Javascript: get DOM element's outerHTML *with* value

I observe that outerHTML for an input doesn't seem to reflect updated values/checks in form inputs. Is there a way for me to get outerHTML for an entire page and have the values/checks included?

To illustrate, I have some form inputs:

<input id="a" type="text" />
<input id="b" type="text" value="ham" />

I can change the values of the inputs, but the outerHTML does not change.

document.getElementById('a').value = 'cheese';
document.getElementById('b').value = 'biscuit';
document.getElementById('a').outerHTML // => <input id="a" type="text" />
document.getElementById('b').outerHTML // => <input id="b" type="text" value="ham" />

If I create a new element and add it to the DOM, document.body.outerHTML holds the new element but still none of the updated values:

const c = document.createElement('input');
c.id = 'c';
c.type = 'text';
document.body.appendChild(c);
document.body.outerHTML /* => <body>
<input id="a" type="text">
<input id="b" type="text" value="ham">
<input id="c" type="text"></body> */

Upvotes: 3

Views: 648

Answers (1)

Manh Nguyen
Manh Nguyen

Reputation: 563

You need to change attribute of element to change outerHTML. Try this:

console.log(document.getElementById("a"));

document.getElementById("a").setAttribute("value", "new value");

console.log(document.getElementById("a"));
<input id="a" type="text" />
<input id="b" type="text" value="ham" />

Upvotes: 1

Related Questions