Categories
JavaScript Answers

How to Set a DOM element as the First Child?

Sometimes, we may want to set a DOM element as the first child element.

In this article, we’ll look at ways to set a DOM element as the first child.

Using the prepend Method

In modern browsers, an HTML element object comes with the prepend method to let us prepend an element as the first child.

For instance, if we have the following HTML:

<div>  
  <p>  
    bar  
  </p>  
  <p>  
    baz  
  </p>  
</div>

Then we can write the following JavaScript to prepend an element as the first child of the div:

const div = document.querySelector('div')  
const newChild = document.createElement('p')  
newChild.textContent = 'foo'  
div.prepend(newChild)

We get the div with the document.querySelector method.

Then we call document.createElement to create an element.

Next, we set the textContent property to add some content to the p element we created.

And then we call div.prepend to prepend newChild as the first child of the div.

There’s also the append method to append an element as the last child of a parent element.

Using the insertAdjacentElement Method

We can also use the insertAdjacentElement method to insert an element as the first child of an element.

For instance, if we have the same HTML:

<div>  
  <p>  
    bar  
  </p>  
  <p>  
    baz  
  </p>  
</div>

Then we can write:

const div = document.querySelector('div')  
const newChild = document.createElement('p')  
newChild.textContent = 'foo'  
div.insertAdjacentElement('afterbegin', newChild)

to call insertAdjacentElement with 'afterbegin' and the newChild to prepend newChild as the first child element of the div.

Other possible values for the first argument of insertAdjacentElement is:

  • beforebegin: before the element itself.
  • beforeend: just inside the element, after its last child.
  • afterend: after the element itself.

Using the insertBefore Method

Another method we can use to prepend an element as the first child is to use the insertBefore method.

For instance, we can write:

const div = document.querySelector('div')  
const newChild = document.createElement('p')  
newChild.textContent = 'foo'  
if (div.firstChild) {  
  div.insertBefore(newChild, div.firstChild);  
} else {  
  div.appendChild(childNode);  
}

given the same HTML we have in the previous examples to prepend newChild as the first child of the div.

We check if there’s a firstChild element attached to the div.

If there is, then we call insertBefore to insert newChild before the firstChild of the div.

Otherwise, we just call appendChild to append newChild as a child element.

Conclusion

We can use various HTML element methods to prepend an element as the first child of a parent element.

Categories
JavaScript Answers

How to Create and Read a Value from a Cookie with JavaScript?

Sometimes, we may want to create and read a value from a cookie with JavaScript.

In this article, we’ll look at how to create and read a value from a cookie with JavaScript.

Creating a Cookie

We can create a cookie by setting the document.cookie property with a string that has the key-value pair with the expires key-value pair attached after it.

For instance, we can write:

const setCookie = (name, value, days = 7, path = "/") => {
  const expires = new Date(Date.now() + days * 864e5).toUTCString();
  document.cookie =
    name +
    "=" +
    encodeURIComponent(value) +
    "; expires=" +
    expires +
    "; path=" +
    path;
};

We create the setCookie function that takes the name , value , days , and path parameters.

name is the key of the cookie.

value is the corresponding value of the key of the cookie.

days is the number of days until it expires.

path is the path for the cookie.

expires has the date string of the expiry date.

toUTCString returns the date string in UTC.

Then we set document.cookie with the name and value with = between it.

And we concatenate that with the expires key-value pair after the semicolon.

And we add the path after that.

Getting a Cookie

There’s no easy way to get a JavaScript cookie with native methods.

We’ve to extract the cookie ourselves given the key.

To do this, we write:

const getCookie = (name) => {
  return document.cookie.split("; ").reduce((r, v) => {
    const parts = v.split("=");
    return parts[0] === name ? decodeURIComponent(parts[1]) : r;
  }, "");
};

We split the document.cookie string with ; .

Then we call reduce on the string array to split the parts by the = sign with split .

Then we check if the first entry of the array is the same as name .

If it is, then we call decodeURIComponent with parts[1] to decode the value.

Otherwise, we return r which has the remaining parts of the split document.cookie string.

The 2nd argument of reduce is an empty string which is the initial return value of reduce .

Now when we call the 2 functions as follows:

setCookie("foo", "bar", 10);
console.log(getCookie("foo"));

We see that the console log should return 'bar' .

Conclusion

We can get and set the document.cookies string property to get and set cookies with JavaScript.

Categories
JavaScript Answers

How to Prepend Values to a JavaScript Array?

Sometimes, we may want to prepend values to a JavaScript array.

In this article, we’ll look at how to prepend values to a JavaScript array.

Array.prototype.unshift

We can use the unshift method to prepend one or more items to an array.

For instance, we can write:

const a = [1, 2, 3, 4];
a.unshift(0);
console.log(a)

unshift prepends an item in place, so we get:

[0, 1, 2, 3, 4]

as the new value of a .

We can pass in as many values as we want, so we can write:

const a = [1, 2, 3, 4];
a.unshift(-1, 0);
console.log(a)

Then we get:

[-1, 0, 1, 2, 3, 4]

as the value of a .

We can also spread an array’s value as arguments of unshift .

For instance, we can write:

const a = [1, 2, 3, 4];
const b = [-1, 0]
a.unshift(...b);
console.log(a)

Then we get the same result as the previous example since we spread the entries of b as arguments of unshift .

Using the Spread Operator

We can also use the spread operator to prepend values to an array.

This will return a new array instead of pretending items in place to an existing array.

For instance, we can write:

const a = [1, 2, 3, 4];
const b = [-1, 0]
const c = [...b, ...a]
console.log(c)

We create the c variable and assign it an array with the values of b spread into the new array first.

Then we spread the entries of a into the same array next.

So c is:

[-1, 0, 1, 2, 3, 4]

as a result.

Array.prototype.concat

Another array method we can use to prepend items to an array is to use the concat method.

It also returns a new array instead of prepending items in-place.

For instance, we can write:

const a = [1, 2, 3, 4];
const b = [-1, 0]
const c = b.concat(a)
console.log(c)

to call concat on b with the array a .

This lets us add the entries from a after the entries of b in the returned array.

So c is [-1, 0, 1, 2, 3, 4] as a result.

Conclusion

We can use various array methods or the spread operator to prepend entries into an array.

Categories
JavaScript Answers

How to Check the Size of a Selected File with JavaScript?

Sometimes, we may want to check the size of a selected file with JavaScript.

In this article, we’ll look at how to check the size of a selected file with JavaScript.

Using the FileReader API

Almost all modern browsers should support the FileReader API.

For instance, we can use it by writing the following HTML:

<form action='#'>
  <input type='file' id='fileinput'>
  <input type='button' id='btnLoad' value='Load'>
</form>

Then we can write the following JavaScript code:

const addPara = (text) => {
  const p = document.createElement("p");
  p.textContent = text;
  document.body.appendChild(p);
}

document
  .getElementById("btnLoad")
  .addEventListener("click", () => {
    const input = document.getElementById('fileinput');
    if (!input.files[0]) {
      addPara("Please select a file before clicking 'Load'");
    } else {
      const file = input.files[0];
      addPara(`File ${file.name} is ${file.size} bytes in size`);
    }
  });

In the HTML code, we have a form with a input with type file .

And we have a button that lets us show the file info when we click it.

In the JavaScript code, we have the addPara function that creates a p element and set the text as its content.

Then we call getElementById to get the button input element.

Then we call addEventListener to add a click listener.

In the click listener, we get the file input with getElementById .

Then we check if input.files[0] exists.

input.files[0] has the first file selected.

If there’s no file, we call addPara to show a message.

Otherwise, we call addPara to show the file info.

file.name has the filename of the selected file.

file.size has the size of the selected file in bytes.

When we select a file and click Load, we should see the file info of the selected file.

Conclusion

We can check the info of the selected file easily with the FileReader API.

Categories
JavaScript Answers

How to Get a Subarray from a JavaScript Array?

Sometimes, we may want to get a subarray from a JavaScript array.

In this article, we’ll look at how to get a subarray from a JavaScript array.

Array.prototype.slice

The JavaScript array’s slice instance method takes the beginning and ending index of the array that we want to extract.

The end index is excluded.

It returns an array with the items starting from the beginning index and the end index minus 1.

For instance, we can write:

const arr = [1, 2, 3, 4, 5];
const sub = arr.slice(1, 3)
console.log(sub)

Then sub is [2, 3] since we extract the array from index 1 to 2 and return it.

We can also pass in negative indexes to the slice method.

Negative indexes mean we start counting from the end of the array instead of the start.

So -1 is the last element of the array, -2 is the 2nd last one, and so on.

So we can replace the code above with:

const arr = [1, 2, 3, 4, 5];
const sub = arr.slice(1, -2)
console.log(sub)

and get the same value for sub .

Conclusion

We can use the JavaScript array’s slice method to extract a subarray from a JavaScript array.