DOM Coding Tips in JavaScript

Suppose you are faced with a task of sufficient complexity, for the implementation of which you need to write a certain number of code lines.

The wrong approach would be to try to write the entire code of the solution as a whole, and then start testing it. In this case, there is a high probability that nothing will work for you, and you will have to look for the error in a large amount of code.

The correct approach is to break the task into small elementary steps that you will implement and immediately check their correctness. In this case, even if you make a mistake somewhere, you will immediately notice the problem and fix it.

Let's try it in practice. Let's say you have paragraphs:

<p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> <p>6</p>

Let your task be to find paragraphs with numbers divisible by 3 and find a sum of those numbers.

As a first small step, I would suggest getting our paragraphs as an array and printing this array to the console to see if we got everything right. Let's do it:

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

The next small step is to loop through our paragraphs and output each of them to the console individually:

let elems = document.querySelectorAll('p'); for (let elem of elems) { console.log(elem); }

And now in a loop we will display the texts of our paragraphs:

let elems = document.querySelectorAll('p'); for (let elem of elems) { console.log(elem.textContent); }

Now let's display the texts of those paragraphs whose number is divisible by 3:

let elems = document.querySelectorAll('p'); for (let elem of elems) { let text = +elem.textContent; if (text % 3 === 0) { console.log(text); } }

After making sure that we get the correct paragraphs, we can proceed to sum their numbers:

let elems = document.querySelectorAll('p'); let sum = 0; for (let elem of elems) { let text = +elem.textContent; if (text % 3 === 0) { sum += text; } } console.log(sum);

Given a list containing the years:

<ul> <li>2000</li> <li>2004</li> <li>2021</li> <li>2022</li> <li>2025</li> <li>2031</li> </ul>

Get years whose sum of digits is 6. Find the sum of the years obtained.