Categories
JavaScript Answers

How to Remove All Child Elements of a DOM Node in JavaScript?

Removing all child elements from a DOM node is something that we’ve to do sometimes in JavaScript.

In this article, we’ll look at how to remove all child elements of a DOM node with JavaScript.

Clearing innerHTML

One way to remove all child elements of an element is to set the innerHTML property of the element to an empty string.

For example, if we have the following HTML:

<button>
  clear
</button>
<div>
</div>

Then we can write the following JavaScript to add the elements to the div.

And we can clear the items when we click the clear button:

const div = document.querySelector('div')
const button = document.querySelector('button')

for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}

button.addEventListener('click', () => {
  div.innerHTML = ''
})

We get the div and the button with document.querySelector .

Then in the for loop, we create the p elements and add them to the div.

And then we call addEventListener on the button with 'click' as the first argument to add a click listener.

Then in the callback, we set div.innerHTML to an empty string to clear its contents when we click the button.

Clearing textContent

Instead of clearing innerHTML , we can clear textContent instead.

To do this, we write:

const div = document.querySelector('div')
const button = document.querySelector('button')

for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}

button.addEventListener('click', () => {
  div.textContent = ''
})

We just switch innerHTML for textContent .

And the rest of the code is the same.

Looping to Remove every lastChild from the DOM

We can remove all the child elements of an element from the DOM with the removeChild method.

For instance, we can write:

const div = document.querySelector('div')
const button = document.querySelector('button')

for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}

button.addEventListener('click', () => {
  while (div.firstChild) {
    div.removeChild(div.lastChild);
  }
})

We have a while loop inside the click listener.

We check if there’re any firstChild elements within the div with div.firstChild .

If there’re, we call removeChuld to remove div.lastChild until there’re no firstChild left.

Looping to Remove every lastElementChild from the DOM

We can also remove every lastElementChild from an element.

To do this, we write:

const div = document.querySelector('div')
const button = document.querySelector('button')

for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}

button.addEventListener('click', () => {
  while (div.lastElementChild) {
    div.removeChild(div.lastElementChild);
  }
})

lastElementChild returns the last child element of the given element.

We can just call removeChild to remove all of them until there’s nothing left.

Conclusion

We can remove all the child elements of an element easily by setting innerHTML or textContent .

Also, we can remove the child elements one by one with removeChild .

Categories
JavaScript Answers

How to Find the Sum of an Array of Numbers with JavaScript?

Finding a sum of an array of numbers is something that we’ve to do a lot in our JavaScript apps.

In this article, we’ll look at how to find the sum of an array of numbers with JavaScript.

Array.prototype.reduce

The JavaScript array’s reduce method lets us get numbers from an array and add them up easily.

To do this, we write:

const sum = [1, 2, 3, 4].reduce((a, b) => a + b, 0)
console.log(sum)

We call reduce with a callback to help us add up the numbers.

a is the accumulated result, which is the partial sum.

And b is the item that we’re iterating through.

In the 2nd argument, we pass in 0 to set the initial result of a .

Therefore, sum is 10.

Lodash sum Method

Lodash has the sum method that is specially made to add up numbers in an array together.

For instance, we can write:

const array = [1, 2, 3, 4];
const sum = _.sum(array);
console.log(sum)

to call sum with the array number array.

Loop

We can use a for-of loop to loop through an array of numbers and add them up.

For instance, we can write:

const array = [1, 2, 3, 4];
let sum = 0
for (const a of array) {
  sum += a
}
console.log(sum)

We get number a from array and add them to sum .

Also, we can use a while loop to loop through the number array.

To do this, we write:

const array = [1, 2, 3, 4];
let sum = 0
let i = 0;
while (i < array.length) {
  sum += array[i];
  i++
}
console.log(sum)

Array.prototype.forEach

We can also use the forEach method to loop through the number array and add up all the numbers.

For example, we can write:

const array = [1, 2, 3, 4];
let sum = 0
array.forEach(a => {
  sum += a;
});
console.log(sum)

We call forEach with a callback.

Then in the callback, we get the value that’s being iterated through with the first parameter.

Then we add that value to the sum .

Conclusion

There’re several ways we can use to find the sum of the numbers in a number array with JavaScript.

One way is to use the reduce method.

Other ways include using the for-of loop, while loop, or forEach to loop through an array.

Categories
JavaScript Answers

How to Get a Random Item From a JavaScript Array?

Getting a random item from a JavaScript array is an operation that we’ve to do sometimes.

In this article, we’ll look at ways to get a random item from a JavaScript array.

Math.random

We can use the Math.random method to return a random index from an array.

Then we can use that to get an element from the array.

For instance, we can write:

const items = [1, 2, 3]
const item = items[Math.floor(Math.random() * items.length)];

Since Math.random returns a number between 0 and 1, we’ve to multiply the returned number by items.length to get an index.

Also, we’ve to use Math.floor to round the number down to the nearest integer to get an index.

Lodash

Lodash has various handy methods we can use to get a random item from an array.

The sample method lets us get a random item from an array.

For instance, we can write:

const items = [1, 2, 3]
const item = _.sample(items);
console.log(item)

We just pass in the array we want to get an item from as the argument.

Also, we can use the random method to pick a random number from 0 up to the given number.

For instance, we can write:

const items = [1, 2, 3]
const item = items[_.random(items.length - 1)]
console.log(item)

We just pass in the max number in the range we want to get.

Also, we can shuffle the entire array and pick the first item from the shuffled array.

To do this, we can use the shuffle method.

For example, we can write:

const items = [1, 2, 3]
const [item] = _.shuffle(items)
console.log(item)

We call shuffle with the items array to return a shuffled version of the items array.

Then we get the first item with destructuring.

Shuffle with sort

We can also shuffle arrays with sort .

For instance, we can write:

const items = [1, 2, 3]
const [item] = items.sort(() => 0.5 - Math.random())
console.log(item)

to shuffle the array by calling sort with a callback that returns a number between -0.5 and 0.5.

This lets us shuffle an array since items are swapped when the returned number is positive.

Conclusion

There’re several ways to get a random item from a JavaScript array.

We can either use native JavaScript methods.

Or we can use convenience methods from Lodash to help us.

Categories
JavaScript Answers

How to Generate a Range of Numbers within the Supplied Bounds?

There’re occasions where we need to generate an array of numbers within the given bounds.

In this article, we’ll look at how to generate a range of numbers within the supplied bounds.

The Array function

We can use the Array constructor as a regular function to create an array with the given size.

Then we can get the indexes with the keys method to get the indexes of an array.

For instance, we can write:

const arr = [...Array(5).keys()];
console.log(arr)

We call keys to return the indexes of the array.

And we spread the items into an array.

Array.from

The Array.from method is a static method that lets us create an array derived from another array.

We can use it to create a number array by using it to map the values to the ones we want.

For instance, we can write:

const lowerBound = 6;
const arr = Array.from(new Array(10), (x, i) => i + lowerBound);
console.log(arr)

The first argument is the array we want to map from.

And the 2nd argument is the mapping function.

x is the entry in from the array in the first argument we’re iterating through.

And therefore, we get:

[6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

as the value of arr .

Lodash

Lodash has the range method that lets us create an array with a range of numbers easily.

It takes up to 3 arguments.

The first is the size of the array to create if there’s only one argument.

If we pass in 2 arguments, then the first number is the starting number and the 2nd is the ending number.

And if we pass in 3 arguments, then the first and 2nd arguments are the same as passing in 2 arguments.

And the 3rd argument is the increment between each number.

For instance, if we write:

const arr = _.range(10);
console.log(arr)

then arr is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] .

If we write:

const arr = _.range(1, 11);
console.log(arr)

Then arr is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] .

And if we write:

const arr = _.range(1, 11, 2);
console.log(arr)

then arr is [1, 3, 5, 7, 9] .

Conclusion

We can create an array of numbers with the Array function.

Also, we can use the Array.from static method.

Another easy way to create a number array is to use Lodash’s range method.

Categories
JavaScript Answers

How to Clear the Canvas for Redrawing?

If we have a canvas, we may want to clear it so that we can draw new things on it.

In this article, we’ll look at how to clear the canvas so that we can draw on it again.

Clear the Canvas for Redrawing

We can clear the canvas easily with the clearRect method, which is part of the canvas context object.

For instance, if we have the following HTML:

<canvas></canvas>
<button>
  clear
</button>

Then we can write:

const canvas = document.querySelector("canvas");
const button = document.querySelector("button");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "green";
ctx.rect(5, 5, 290, 140);
ctx.stroke();

button.addEventListener('click', () => {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
})

to draw something and add a click listener to the button to clear the canvas when we click the button.

We call getContext to get the context object.

Then we call beginPath to start drawing.

And we set the lineWidth to set the width of the line.

strokeStyle sets the stroke style.

rect draws the rectangle with the x and y coordinates of the top left corner and the width and height respectively.

And the stroke method draws the rectangle.

Next, we call addEventListener with the 'click' to add a click listener to the button.

And the callback runs when we click the button.

We call clearRect with the canvas context with the same arguments as rect .

It clears the canvas instead of drawing on it.

Transformed Coordinates

If we added coordinate transformations to our canvas, then we’ve to add more code to save the transformation matrix first.

Then we can clear the canvas, and then restore the transformation matrix.

To do this, we write:

const canvas = document.querySelector("canvas");
const button = document.querySelector("button");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "green";
ctx.rect(5, 5, 290, 140);
ctx.stroke();

button.addEventListener('click', () => {
  ctx.save();
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.restore();
})

In the callback, we call save to save the transformation matrix.

setTransform set the transformation to the identity matrix to remove the transformation.

Then we call clearRect to clear the canvas.

And we call restore to restore the transformation.

Conclusion

We can clear the canvas by calling the clearRect method.

If we have transformed coordinates, then we can save the transformation matrix, clear the canvas, and then restore the transformation matrix.