Attributes And Properties Reflect Differently
The value attribute seeds the DOM property but they diverge once code or a user edits it; serializing forms must read properties, not getAttribute strings.
Code
// attribute 写在 HTML 标记上(字符串);property 是 DOM 对象上的 JS 值
const input = document.createElement('input');
input.setAttribute('value', 'typed in markup');
console.log('property picks up attribute:', input.value);
// 用户或代码改过 property 之后:两者从此各自独立
input.value = 'typed by user';
console.log('attribute unchanged:', input.getAttribute('value'));
console.log('property now:', input.value);
// checked 同理:attribute 是初始默认值,property 是当前状态
const box = document.createElement('input');
box.type = 'checkbox';
box.setAttribute('checked', '');
console.log('defaultChecked:', box.defaultChecked, '| checked:', box.checked);
box.checked = false;
console.log('after uncheck:', box.defaultChecked, box.checked, '| attr present:', box.hasAttribute('checked'));How the snippet works
Module-level bindings hold the data — input, box — with no function scope in between.
What to watch for
- Uses
document, so it needs a browser context — it will not run as-is in Node without shims.
Using it
Running the file prints labeled results such as property picks up attribute:, attribute unchanged:, property now: — each operation’s effect is visible in the output.
Key statements
input.setAttribute('value', 'typed in markup');
const input = document.createElement('input');
const box = document.createElement('input');
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.Properties File ParserParse Java .properties files with comments, continuations, separators, and escapes, then emit clean JSON.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does Attributes And Properties Reflect Differently run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.