⊗jsSpItDEN 76 of 281 menu

DOM elements numbering in JavaScript

Understanding iterators makes it easy to add numbers to DOM elements. Let, for example, we have paragraphs:

<+html+>

text

text

text

<-html->

Let's get a collection of these paragraphs into a variable:

let elems = document.querySelectorAll('p');

Let's use the built-in iterator entries to iterate:

for (let entry of elems.entries()) { console.log(entry); }

Let's use destructuring to separate numbers from elements:

for (let [num, elem] of elems.entries()) { console.log(num, elem); }

We add a paragraph number to the end of each paragraph:

for (let [num, elem] of elems.entries()) { elem.textContent += num; }

Given an HTML table. Number each cell in this table.

enru