You don't want innerHTML
for this, you just want to access the HTMLInputElement
within that cell.
You can do it like this, but it's fragile:
cell.firstChild.checked
I'd probably use querySelector
to find the first input
within the cell:
cell.querySelector("input").checked
Similarly, I probably wouldn't use cellIndex === 0
, so I could change the layout without breaking my code. So for instance:
let table = document.getElementById("hosts");
for (let row of table.rows) {
for (let cell of row.cells) {
const checkbox = cell.querySelector("input[type=checkbox]");
if (checkbox && checkbox.checked) {
// ...this cell has a checked checkbox in it...
}
}
Side note:
Beware, the HTMLCollection
returned by rows
and cells
is not defined as being iterable, but you're relying on it being iterable by using for-of
. Some browsers make it iterable even though it isn't specified, but others don't.
If you're doing this in a page or application (not a library), you can ensure that HTMLCollection
is iterable by polyfilling it like this:
if (typeof HTMLCollection !== "undefined" && HTMLCollection.prototype && !HTMLCollection.prototype.forEach) {
// Yes, there's really no need for `Object.defineProperty` here
HTMLCollection.prototype.forEach = Array.prototype.forEach;
if (typeof Symbol !== "undefined" && Symbol.iterator && !HTMLCollection.prototype[Symbol.iterator]) {
Object.defineProperty(HTMLCollection.prototype, Symbol.iterator, {
value: Array.prototype[Symbol.itereator],
writable: true,
configurable: true
});
}
}
See this answer doing that for NodeList
(which is defined as iterable) for details.
Alternately, use querySelectorAll
on the table and rows instead:
for (let row of table.querySelectorAll("tr")) {
for (let cell of row.querySelectorAll("td")) {
// ...
}
}