Categories
JavaScript Answers

How to Loop Through Each Item in a JavaScript FileList?

Sometimes, we want to loop through each item in a JavaScript file list.

In this article, we’ll look at how to loop through each item in a JavaScript file list object.

Convert the FileList Object with the Array.from Method and Use the Array.prototype.forEach Method

One way to let us loop through each item in a file list object is to convert it to an array with the Array.from method.

Then we can use the forEach method on it to loop through the file list entries.

For instance, if we have the following file input:

<input type='file' multiple>

Then we can get the input and listen to the change event of the file input to get the selected files after they’re selected:

const input = document.querySelector('input');
input.addEventListener('change', () => {
  Array.from(input.files)
    .forEach(file => {
      console.log(file)
    });
})

The file input has the multiple attribute so that we can select multiple files.

We call addEventListener on the input to add a change listener to it.

We call Array.from method to convert the input.files file list to an array with the selected files.

input.files is the file list object with the selected files.

Then we can call the forEach method to loop through each file.

Convert the FileList Object with the Spread Operator and Use the Array.prototype.forEach Method

Another way to convert the file list object to an array is to use the spread operator.

This works since a file list is an iterable object.

For instance, we can write:

const input = document.querySelector('input');
input.addEventListener('change', () => {
  [...input.files]
  .forEach(file => {
    console.log(file)
  });
})

to spread the input.files entries into an array.

Then we can call forEach on it as we did before.

Use the for-of Loop

Since the file list object is an iterable object, we can also use the for-of loop on it to loop through each file list entry.

For instance, we can write:

const input = document.querySelector('input');
input.addEventListener('change', () => {
  for (const file of input.files) {
    console.log(file)
  }
})

to loop through each entry of input.files with the for-of loop.

Conclusion

We can convert the file list object to an array and use the forEach method or use the for-of loop to loop through each item in the file list.

Categories
JavaScript Answers

How to Find the Position Index of a Regex Match Result in JavaScript?

Sometimes, we want to find the index of the regex match in our JavaScript code.

In this article, we’ll look at how to find the index of a regex match with JavaScript.

Use the RegExp.prototype.exec Method

We can use the JavaScript regex’s exec method to find the index of a regex match.

For instance, we can write:

const match = /bar/.exec("foobar");  
console.log(match && match.index);

We call exec on /bar/ with 'foobar' as the argument to find the bar pattern in the 'foobar' string.

If match isn’t null , then it should have the match.index property with the first index of the matched substring in the 'foobar' string.

Since 'bar' starts at index 3, match.index should be 3.

We can also use it to get the index of all the matches in a string.

For instance, we can write:

const re = /bar/g,  
  str = "foobarfoobar";  
while ((match = re.exec(str)) !== null) {  
  console.log(match && match.index);  
}

re has the g flag to let us search for all the matches of a pattern in a string.

We loop through the results returned by re.exec with the while loop.

If the returned result isn’t null , then we keep getting the matched results until it returns null .

match.index therefore should be 3 and 9 since the first 'bar' starts at index 3 and the 2nd 'bar' starts at index 9.

Conclusion

We can find the indexes of one or more matches of a regex pattern within a JavaScript string by using the RegExp.prototype.exec method.

Categories
JavaScript Answers

How to Select an HTML Element by their textContent Value with JavaScript?

Sometimes, we want to select an HTML element by their textContent value with JavaScript.

In this article, we’ll look at how to select an HTML element by their textContent value with JavaScript.

Select Elements with document.querySelectorAll and Loop Through Them to Find the Ones We Want

We can select multiple elements with document.querySelectorAll .

Then we can loop through them to find the ones we want with the for-of loop.

For instance, if we have the following HTML:

<div>
  foo
</div>
<div>
  bar
</div>
<div>
  baz
</div>

Then we can the div with text ‘bar’ by writing:

const divs = document.querySelectorAll("div");
const searchText = "bar";

for (const div of divs) {
  if (div.textContent.includes(searchText)) {
    console.log(div.textContent)
  }
}

We select all the divs with document.querySelectorAll .

Then we loop through each item with the for-of loop.

In the loop body, we check if div.textContent includes the searchText with the includes method.

If it does, then we log it with console log.

Therefore, we should see the console log log 'bar' as a result.

Search for an Element with the Given Text Content by XPath

Another way to search for an element with the given text content is to use an XPath.

For instance, if we have the following HTML:

<div>
  foo
</div>
<div>
  bar
</div>
<div>
  baz

Then we can the div with text ‘bar’ by writing:

const xpath = "//div[contains(text(),'bar')]";
const matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
console.log(matchingElement)

using the xpath string.

xpath is a string that specifies we match the div elements that contains the text ‘bar’.

Then we can use the xpath string to search for the element we want by calling the document.evaluate method with the xpath as the first argument.

document is the 2nd argument which means we’re search the whole document for the element.

singleNodeValue returns the first element node that matches the XPath we’re using to search.

Therefore, matchingElement should be the div element with text content ‘bar’.

Conclusion

We can search for an element with the given text content by selecting elements and looping through them to find it.

Or we can search for it with an XPath.

Categories
JavaScript Answers

How to Add Options to an HTML select Element with JavaScript?

Sometimes, we want to add options to an HTML select element with JavaScript.

In this article, we’ll look at how to add options to an HTML select element with JavaScript.

Using the document.createElement Method

We can use the document.createElement method to create a new option element.

Then we can call appendChild on the select element to append it as a child of the select element.

For instance, we can write the following HTML:

<select>

</select>

to create an empty select element.

Then we can add the option elements for the select element by writing:

const select = document.querySelector('select')
const arr = ['apple', 'orange', 'grape']
for (const [index, a] of arr.entries()) {
  const opt = document.createElement('option');
  opt.value = index;
  opt.innerHTML = a;
  select.appendChild(opt);
}

We get the select element with document.querySelector .

Then we define the arr array with the option text we want to add.

Next, we have a for-of loop to loop through the arr entries.

We call arr.entries to return an array with the index and the value of the array entry each in their own array.

In the loop body, we call document.createElement to create the option element.

Next, we set the value property to set the value of the value attribute of the option element.

Then we set the innerHTML property to set the content that the user sees in the drop-down for each option.

And finally, we call select.appendChild with the opt element object to add it as a child of the select element.

Therefore, now we should see a drop-down with apple, orange, and grape as options.

Conclusion

We can add options into the select HTML element with the document.createElement method.

Then we can append the created option element to the select element with appendChild .

Categories
JavaScript Answers

How to Join or Combine Two JavaScript Arrays by Concatenating Them into One Array?

Sometimes, we want to combine 2 JavaScript arrays by concatenating them into one array.

In this article, we’ll look at how to join or combine 2 JavaScript arrays by concatenating them into one array.

Use the Array.prototype.concat Method

One way to join 2 Javascript arrays by concatenating them into one array is to use the JavaScript array’s concat method.

For instance, we can write:

const a = ['a', 'b', 'c'];
const b = ['d', 'e', 'f'];
const c = a.concat(b);
console.log(c)

We call a.concat(b) to add the entries of b after the entries of a and return the new array with all the entries.

Therefore, c is:

["a", "b", "c", "d", "e", "f"]

Use the Spread Operator

Another way to combine 2 arrays by joining them together is to use the spread operator.

For example, we can write:

const a = ['a', 'b', 'c'];
const b = ['d', 'e', 'f'];
const c = [...a, ...b]
console.log(c)

We spread the entries of a and b into a new array to form the c array.

They’ll be spread in the same order that they’re listed.

Therefore, c is now:

["a", "b", "c", "d", "e", "f"]

Conclusion

We can use the JavaScript array’s concat method or the spread operator to combine 2 JavaScript arrays by joining them together.