Categories
JavaScript Answers

How to use HTML5/JavaScript to generate and save a file?

To use HTML5/JavaScript to generate and save a file, we create a link.

For instance, we write

const link = document.createElement("a");
link.setAttribute(
  "href",
  "data:text/plain;charset=utf-8," + encodeURIComponent(text)
);
link.setAttribute("download", filename);
link.click();

to call createElement to create a link.

Then we call setAttribute to set the href attribute to the base64 URL of the file we want to download.

We call setAttribute again to set the download attribute to the name of the downloaded file.

Finally, we call click to download the file.

Categories
JavaScript Answers

How to make an HTML back link with JavaScript?

To make an HTML back link with JavaScript, we call the history.back method on click.

For instance, we write

<a href="javascript:history.back()">Go Back</a>

to set the href attribute to the JavaScript code that calls the history.back method to go back to the previous page when we click on the link.

Categories
JavaScript Answers

How to check whether a Storage item is set with JavaScript?

To check whether a Storage item is set with JavaScript, we use the getItem method.

For instance, we write

if (localStorage.getItem("infiniteScrollEnabled") === null) {
  //...
}

to check if the local storage item with key 'infiniteScrollEnabled' with the getItem method.

If it’s null, then the item with key 'infiniteScrollEnabled' doesn’t exist in local storage.

Categories
JavaScript Answers

How to load up CSS files using JavaScript?

To load up CSS files using JavaScript, we create an element with createElement.

For instance, we write

const link = document.createElement("link");
link.href = src;
link.rel = "stylesheet";
document.head.append(link);

to call createElement to create a link element.

And then we set its href and rel attributes by setting the properties with the same name.

Then we call document.head.append to append the link element as the last child of the head element.

Categories
JavaScript Answers

How to parse an HTML string with JavaScript?

To parse an HTML string with JavaScript, we create an element and put the HTML inside it.

For instance, we write

const el = document.createElement("html");
el.innerHTML =
  "<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>";

const links = el.getElementsByTagName("a");

to call createElement to create the html element.

Then we set its innerHTML property to the HTML string we want to parse.

Next, we get the links from el with getElementsByTagName.