Hi FreeCodeCamp!
I am a beginner coder working on some DOM manipulation in JavaScript. The assignment is to dynamically create a table when clicking the ‘Submit’ button, and to be able to click any square in the table and change the color to the color of the color selector element.
So far, the table creation is working, and the color selection is not. No matter what, the color changes only work before I create the table.
I also have a click listener on the h1 element, which confusingly does change to the correct color.
// Declare variables for the two number elements, and the submit button
var submit = document.getElementById('submit');
var inputWidth = document.getElementById('inputWidth');
var inputHeight = document.getElementById('inputHeight');
// Add a click listener to the Submit button that removes the existing table, and makes a new one based on the input height and with.
submit.addEventListener('click', function () {
var table = document.querySelector('table');
document.body.removeChild(table);
var table = document.createElement('table')
document.body.appendChild(table);
table.setAttribute('id', "table");
for (i = 0; i < inputHeight.value; i++) {
var tr = document.createElement('tr');
table.appendChild(tr);
for (j = 0; j < inputWidth.value; j++) {
var td = document.createElement('td');
tr.appendChild(td);
}
}
tds = document.querySelectorAll('td');
console.log(tds);
});
// Attempt to change color of a clicked 'td' element after the table has been created (Not working)
console.log(document.querySelector('body'));
var tds = document.querySelectorAll('td');
console.log(tds)
console.log(document.querySelector('body'));
for (const td of tds) {
var colorSelectorColor = colorSelector.value;
console.log(td);
td.addEventListener('click', function () {
td.style.backgroundColor = colorSelectorColor;
});
}
// ----Test Color Selector on H1 Header---- Works Better //
var h1 = document.getElementById("h1");
var table = document.getElementById("table");
var colorSelectorColor = document.getElementById("colorSelector").value;
console.log(colorSelectorColor);
h1.addEventListener('click', function () {
var colorSelector = document.getElementById("colorSelector");
h1.style.color = colorSelector.value;
console.log(h1.style.color.value);
});