I am trying to display a basic set and allow a user to add elements to the set. Here is what I have thus far:
<head>
<script>
class _Set extends Set {
add(...args) {
for (const x of args) {
this.add(x)
}
return this;
}
}
const s = new Set();
const button = document.querySelector('button');
const text = document.getElementById('theText');
button.addEventListener('click', () => {
let values, rawValue = document.getElementById('theValue');
if (rawValue.includes(',')) {
values = rawValue.split(',').map(x => x.trim());
} else {
values = [rawValue,];
}
for (value of values) {
s.add(value);
}
text.textContent = `Set(${s.size}) = ${Array.from(s)}`;
});
</script>
</head>
<body>
<input type="text" id="theText" placeholder="Enter in a value"/>
<input type="button" value="submit"/>
Your set now contains: <span id="theSet">{}</span>
</body>
I suppose this error is occurring because the javascript tries running before the html dom has been rendered and is ready for scripting. What am I doing wrong here and what would be the correct way to do something such as the above?