Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.
In this article, we’ll look at some solutions to common JavaScript problems.
Parse an HTML String with JavaScript
We can parse an HTML string with JavaScript by creating an html
element that we don’t attach to the DOM.
Then we can use that to get what we want/
For instance, if we have:
const html = `
<html>
<head>
<title>title</title>
</head>
<body><a href='test'>link</a></body>
</html>
`
Then we can write:
const el = document.createElement('html');
el.innerHTML = html;
const anchor = el.querySelector('a');
We create the html
element with createElement
.
Then we set innerHTML
with html
to populate the items in the string in the new element.
Then we can use any DOM method like querySelector
to get the element within the HTML.
There’s also the DOMParser
constructor that’s used to parse the DOM.
For example, we can write:
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, 'text/htm;');
Where html
is the same string as we have before.
Convert String into Float
We can use the parseFloat
function to parse a string into a floating-point number.
For instance, we can write:
const value = parseFloat("123.45");
We parse 123.45 into a floating-point number with it.
If we use decimal separators that aren’t periods, then we’ve to replace it with a period.
For instance, we can write:
const value = parseFloat("123,45".replace(",", "."));
Custom Attributes in HTML
If we want to add custom attributes to our elements, then we’ve to prefix it with the data-
prefix.
For instance, we write:
<p data-date-changed="2020-01-01">Hello</p>
Then we can get the attribute value with getAttribute
:
const dateChanged = document.querySelector("p").getAttribute("data-date-changed");
Get the YouTube video ID from a URL
We can get the YouTube video ID from the URL by splitting the query string.
To do that, we can use the URLSearchParams
constructor.
For instance, we can write:
const urlSearchParams = new URLSearchParams(window.location.search.slice(1))
const videoId = urlSearchParams.get('v');
The first line creates the URLSearchParams
instance with the query string.
We take out the ?
from the window.location.search
string by using lice
.
Then we call get
with the query parameter key v
.
And videoId
would be the video ID.
Import Modules from all Files in a Directory
We can import all modules from a directory if we export everything from each module.
So in one module, we can write:
things/index.js
export * from './moduleA';
export * from './moduleB';
export * from './moduleC';
Then we can import everything by writing:
import { ModuleA, ModuleB, ModuleC } from './things';
We export everything in each module in index.js
.
Then we import them in another module.
We can do the same thing with default exports.
For example, we can write:
things/index.js
export { default as ModuleA } from './moduleA'
export { default as ModuleB } from './moduleB'
export { default as ModuleC } from './moduleC'
Then we can import them by writing:
import { ModuleA, ModuleB, ModuleC } from './things'
Difference Between innerText and innerHTML
The difference between innerText
and innerHTML
is that innerText
only works with plain text.
Everything set as its value would be interpreted as plain text.
On the other hand, innerHTML
would interpret HTML text as HTML and render them on the screen.
Resolve the C:fakepath When File is Selected from a File Input
We can’t get the full file path when we select the file input.
However, we can read the content of the file into a string.
For instance, we can write:
const input = document.querySelector("input");
input.onchange = () => {
const fileReader = new FileReader();
fileReader.readAsDataURL(input.files[0]);
fileReader.onloadend = (event) => {
console.log(event.target.result);
}
}
The input
element is input with type file
.
We can watch for file changes by setting a listener to the onchange
property.
Then we create a new FileReader
instance and call the readAsDataURL
method to read the data as a base64 string.
The onloadend
listener attached to fileReader
will run when the file is read.
event.target.result
has the base64 string, which has the complete content of the file.
Conclusion
We can parse an HTML string by setting the string to innerHTML
or use the DOMParser
.
We can convert a string to a float with parseFloat
.
To read a file’s content when it’s selected, we can use the FileReader
constructor.
Also, we can export everything from a module with *
.