Categories
JavaScript Answers

How to Insert a Row in an HTML Table Body in JavaScript?

Sometimes, we want to insert a row in an HTML table body with JavaScript.

In this article, we’ll look at how to insert a row in an HTML table body with JavaScript.

Call the insertRow and insertCell Methods

JavaScript DOM API has the insertRow method built into the tbody element.

And it also has the insertCell method built into the tr element.

insertRow lets us insert a new table row.

And insertCell method lets us insert a new cell into a table row.

For instance, if we have the following HTML:

<table id="myTable">
  <thead>
    <tr>
      <th>My Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>aaaaa</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>My footer</td>
    </tr>
  </tfoot>
</table>

We can write:

const tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

const newRow = tbodyRef.insertRow();
const newCell = newRow.insertCell();
const newText = document.createTextNode('new row');
newCell.appendChild(newText);

We have a table, with the tbody element inside.

Then to get the tbody , we call getElementId to get the table.

Then we call getElementsByTagName to get the tbody element.

Next, we call insertRow on the tbody element to create a new tr.

And then we call insertRow on the newly created tr .

Next, we call document.createTextNode to create a new text node for the table cell content.

And then we call newCell.appendChild to append the newText text node.

Now we should see ‘new row’ before the footer.

Conclusion

We can use methods built into tbody and tr DOM objects to insert new table rows and cells with JavaScript.

Categories
JavaScript Answers

What’s the Most Accurate Way to Check a JavaScript Object’s Type?

On many occasions, we would need to check for a JavaScript object’s data type because of its dynamic nature.

In this article, we’ll look at the most accurate way to check for JavaScript object’s type.

Use typeof for Primitive Values

We should use the typeof for checking primitive values except null

For instance, if we have:

console.log(typeof 1)  
console.log(typeof '')  
console.log(typeof true)  
console.log(typeof 1n)  
console.log(typeof undefined)  
console.log(typeof Symbol())

We use typeof to get the type for numbers, booleans, bigints, undefined , and symbols.

Therefore, we get:

number  
string  
boolean  
bigint  
undefined  
symbol

from the console log.

Since typeof null returns 'object' , we can’t use it to check if an expression returns null .

Use Object.getPrototypeOf to Get the Prototype of an Object

We can check the prototype of an object with the getPrototypeOf method.

For instance, if we have:

const o = {}  
const proto = Object.getPrototypeOf(o);  
console.log(proto === Object.prototype);

Then the console log logs true since an object literal inherits from Object.prototype .

We just pass in the object we get the prototype from with the Object.getPrototypeOf method.

And if we created an object from a constructor, we can do the same check.

For instance, we can write:

const o = new Date()  
const proto = Object.getPrototypeOf(o);  
console.log(proto === Date.prototype);

to check that o is created from the Date constructor.

This should also log true since o is created by instantiating Date .

Conclusion

We should use typeof to check the type of primitive values.

And we can use the Object.getPrototypeOf method to check for an object’s prototype.

Categories
JavaScript Answers

What’s the Difference Between ++x and x++ in JavaScript?

In JavaScript, we can increment the value of a numeric variable in 2 ways.

We can put ++ before or after the variable.

They look similar but they’re different.

In this article, we’ll look at the differences between ++x and x++ in JavaScript.

The difference between ++x and x++ is the ++x increments the variable and returns the new value of x as the value.

For instance, if we write:

let x = 1  
console.log(++x)  
console.log(x)

Then we see that both console logs log 2.

On the other hand, x++ increments the variable but it doesn’t return the new value of x as the value.

For instance, if we have:

let x = 1  
console.log(x++)  
console.log(x)

Then we see that the first console log logs 1, and the 2nd console log logs 2.

Conclusion

Even though ++x and x++ looks similar, they’re different.

++x increments the variable and returns the new value of x as the value.

While x++ increments the variable but it doesn’t return the new value of x as the value.

Categories
JavaScript Answers

How to Loop Through a Date Range with JavaScript?

Sometimes, we want to loop through a date range with JavaScript.

In this article, we’ll look at how to loop through a date range with JavaScript.

Using a while Loop

One way to loop through a date range with JavaScript is to use a while loop.

We can create variables for the start and end dates.

Then we can increment the start date until it reaches the end date.

To do this, we write:

const start = new Date("02/05/2020");
const end = new Date("02/10/2020");

let loop = new Date(start);
while (loop <= end) {
  console.log(loop);
  let newDate = loop.setDate(loop.getDate() + 1);
  loop = new Date(newDate);
}

We have the start and end variables with the start and end date respectively.

Then we create the loop variable that we use as the looping variable.

We increment the date of loop until it reaches end .

We do the incrementing by calling setDate with the loop.getdate() + 1 .

getDate lets us get the day of the month.

We assign the returned date to loop to increment it.

Therefore, we get:

Wed Feb 05 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Thu Feb 06 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Fri Feb 07 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Sat Feb 08 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Sun Feb 09 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Mon Feb 10 2020 00:00:00 GMT-0800 (Pacific Standard Time)

from the console log.

Conclusion

We can loop through a date range with a while loop with a looping variable that’s set to the start date.

Then we increment the looping variable until it reaches the end date.

Categories
JavaScript Answers

How to Remove HTML Elements by Class Name?

Sometimes, we want to remove HTML elements by class name in our JavaScript code.

In this article, we’ll look at how to remove elements by class name.

Get the Parent Node of the Element and call removeChild on it

We can get the parent node of the element and call removeChild on each element to remove an element.

For instance, if we have the following HTML:

<div>  
  <p class='text'>  
    foo  
  </p>  
  <p class='text'>  
    bar  
  </p>  
  <p class='text'>  
    baz  
  </p>  
</div>

Then we can write:

const text = document.querySelectorAll('.text')  
for (const el of text) {  
  el.parentNode.removeChild(el);  
}

to select all the elements with the class text .

Then we use the for-of loop to loop through each element.

In the loop body, we get the parent node of the element with the parentNode property.

Then we call removeChild with the el element to remove it.

Call the remove Method

Element objects also have the remove method to let us remove an element.

For instance, if we have the following HTML:

<div>  
  <p class='text'>  
    foo  
  </p>  
  <p class='text'>  
    bar  
  </p>  
  <p class='text'>  
    baz  
  </p>  
</div>

Then we can write:

const text = document.querySelectorAll('.text')  
for (const el of text) {  
  el.remove();  
}

to remove each element selected with the remove method.

Conclusion

We can select all the elements with a given class and then remove them one by one in the for-of loop.

Each element can be removed with the remove or removeChild method.