简体   繁体   English

Javascript:获取 DOM 元素的 outerHTML *with* value

[英]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.我观察到输入的outerHTML似乎没有反映表单输入中的更新值/检查。 Is there a way for me to get outerHTML for an entire page and have the values/checks included?有没有办法让我获得整个页面的outerHTML并包含值/检查?

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.我可以更改输入的值,但 outerHTML 不会更改。

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:如果我创建一个新元素并将其添加到 DOM, document.body.outerHTML会保存新元素,但仍然没有更新值:

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> */

You need to change attribute of element to change outerHTML.你需要改变元素的属性来改变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" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM