Categories
JavaScript Answers

How to Turn All the Keys of a JavaScript Object to Lower Case?

Sometimes, we want to turn all the keys of a JavaScript object to lower case.

In this article, we’ll look at how to turn all the keys of a JavaScript object to lower case.

Turn All the Keys of a JavaScript Object to Lower Case

To turn all the keys of a JavaScript object to lower case, we can use the Object.entries method to convert the object to an array with the key-value pair arrays.

Then we can use the JavaScript array map method to map the keys to lower case.

And finally, we use the Object.fromEntries method to convert the mapped key-value pair array back to an object.

For instance, we can write:

const obj = {
  FOO: 1,
  BAR: 2,
  BAZ: 3
}
const newObj = Object.fromEntries(
  Object.entries(obj).map(([k, v]) => [k.toLowerCase(), v])
);
console.log(newObj)

We have the obj object with property key names that are all in upper case.

To convert all the key names to lower case, we call Object.entries with obj to map all the object properties to key-value pair arrays in an array.

Then we call map with a callback that returns the k key converted to lower case with toLowerCase .

The property value v stays unchanged.

And then we call Object.fromEntries to convert the key-value pair array back to an object and assigned the returned object to newObj.

Therefore newObj is:

{
  "foo": 1,
  "bar": 2,
  "baz": 3
}

according to the console log.

Conclusion

To turn all the keys of a JavaScript object to lower case, we can use the Object.entries method to convert the object to an array with the key-value pair arrays.

Then we can use the JavaScript array map method to map the keys to lower case.

And finally, we use the Object.fromEntries method to convert the mapped key-value pair array back to an object.

Categories
JavaScript Answers

How to Check if an Element is a Div with JavaScript?

Sometimes, we want to check if an element is a div with JavaScript.

In this article, we’ll look at how to check if an element is a div with JavaScript.

Check if an Element is a Div with JavaScript

To check if an element is a div with JavaScript, we can get the tagName property of an element.

For instance, if we have the following HTML:

<div>
  foo
</div>
<p>
  bar
</p>

Then we can write:

for (const el of document.querySelectorAll('*')) {
  if (el.tagName.toLowerCase() === "div") {
    //it's a div
    console.log(el)
  } else {
    //it's not a div
  }
}

to select all the elements in the HTML with document.querySelectorAll and loop through the selected elements with the for-of loop.

Then in the loop body, we get the tag name of each element with the tagName property.

We call toLowerCase to convert the tag name to lower case.

Then we can check if el is a div by comparing it against 'div' .

If it’s a div, then we log it.

And we should see the div in the console log.

Conclusion

To check if an element is a div with JavaScript, we can get the tagName property of an element.

Categories
JavaScript Answers

How to Get an Element’s Padding Value Using JavaScript?

Sometimes, we want to get an element’s padding value using JavaScript.

In this article, we’ll look at how to get an element’s padding value using JavaScript.

Get an Element’s Padding Value Using JavaScript

To get an element’s padding value using JavaScript, we can use the getComputedStyle and getPropertyValue methods.

For instance, if we have the following HTML:

<div style='padding: 20px'>  
  hello world  
</div>

Then we can get the padding-left value of the div by writing:

const div = document.querySelector('div')  
const paddingLeft = window.getComputedStyle(div, null).getPropertyValue('padding-left')  
console.log(paddingLeft)

We call document.querySelector to get the div.

Then we call window.getComputedStyle with the div to get the computed CSS styles of the div.

Then we call getPropertyValue with 'padding-left' to get the padding-left CSS property value.

Therefore, paddingLeft is '20px' according to the console log.

Conclusion

To get an element’s padding value using JavaScript, we can use the getComputedStyle and getPropertyValue methods.

Categories
JavaScript Answers

How to fix the ESLint Warning “Function declared in a loop contains unsafe references to variable(s)…no-loop-func” with JavaScript?

To fix the ESLint Warning "Function declared in a loop contains unsafe references to variable(s)…no-loop-func" with JavaScript, we shoyuld replace loops with forEach.

For instance, we write

const showHelp = (help) => {
  document.getElementById("help").textContent = help;
};

const setupHelp = () => {
  const helpText = [
    { id: "email", help: "Your e-mail address" },
    { id: "name", help: "Your full name" },
    { id: "age", help: "Your age (you must be over 16)" },
  ];

  helpText.forEach((text) => {
    document.getElementById(text.id).onfocus = () => {
      showHelp(text.help);
    };
  });
};

to call helpText.foreach with a callback to set the document.getElementById(text.id).onfocus to a function that calls showHelp.

Using forEach confines toe scope of the functions within the block so we won’t get unexpect results when the onfocus callback runs.

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.