Categories
JavaScript Answers

How to programmatically empty browser cache with JavaScript?

To programmatically empty browser cache with JavaScript, we call the caches.delete method.

For instance, we write

const keyList = await caches.keys();
await Promise.all(keyList.map((key) => caches.delete(key)));

to get a promise with the cache keys with caches.keys.

Then we delete the cache values with the given key with caches.delete.

Categories
JavaScript Answers

How to get the pure text without HTML element using JavaScript?

To get the pure text without HTML element using JavaScript, we can use the textContent property.

For instance, we write

const element = document.getElementById("txt");
const text = element.textContent;

to select the element with getElementById.

And then we get the textContent property to get the pure text inside the element.

Categories
JavaScript Answers

How to submit a form with JavaScript by clicking a link?

To submit a form with JavaScript by clicking a link, we can add a button and attach a click listener to it.

For instance, we write

<form id="form-id">
  <button id="your-id">submit</button>
</form>

to add a form.

Then we write

const form = document.getElementById("form-id");

document.getElementById("your-id").addEventListener("click", () => {
  form.submit();
});

to select the form with getElementById.

And then we select the button with getElementById and add a click listener to it with addEventListener.

In the click listener, we call form.submit to submit the form.

Categories
JavaScript Answers

How to detect which one of the defined font was used in a web page with JavaScript?

To detect which one of the defined font was used in a web page with JavaScript, we use the font property.

For instance, we write

const font = document.getElementById("header").style.font;

to select the element with getElementById.

And then we get the font used with the style.font property.

Categories
JavaScript Answers

How to count text lines inside an DOM element with JavaScript?

To count text lines inside an DOM element with JavaScript, we can calculate it from the element height and its line height.

For instance, we write

const el = document.getElementById("content");
const divHeight = el.offsetHeight;
const lineHeight = parseInt(el.style.lineHeight);
const lines = divHeight / lineHeight;
console.log(lines);

to get the element with getElementById.

We get its height with offsetHeight.

We get its line height with el.style.lineHeight.

Then we divide divHeight by lineHeight to get the number of lines.