Categories
JavaScript Answers

How to append to innerHTML without destroying descendants’ event listeners with JavaScript?

To append to innerHTML without destroying descendants’ event listeners with JavaScript, we need to use DOM methods.

For instance, we write

<div id="myDiv">
  <span id="mySpan">foo</span>
</div>

to add the div and span.

const mySpan = document.getElementById("mySpan");
mySpan.onclick = () => {
  alert("hi");
};

const myDiv = document.getElementById("myDiv");
myDiv.appendChild(document.createTextNode("bar"));

to get the span with getElementById.

And we add a click listener to it by setting the onclick property to the click listener.

Then we get the div with getElementById and then call appendChild on it to append a text node as its last child.

We create the text node with createTextNode.

Then span’s click listener is kept after we call appendChild.

Categories
JavaScript Answers

How to get element at specified position with JavaScript?

To get element at specified position with JavaScript, we use the elementFromPoint method.

For instance, we write

const elem = document.elementFromPoint(2, 2);

to call document.elementFromPoint with the coordinate of the element to get to return the element at the coordinates.

Categories
JavaScript Answers

How to download a PDF file instead of opening them in browser when clicked with HTML?

To download a PDF file instead of opening them in browser when clicked with HTML, we add the download attribute.

For instance, we write

<a href="dummy.pdf" download="filename.pdf">download</a>

to add the download attribute and set it to the file name of the downloaded file to make the file download instead of opening it.

Categories
JavaScript Answers

How to change element style attribute dynamically using JavaScript?

To change element style attribute dynamically using JavaScript, we call the style.setProperty method.

For instance, we write

document.getElementById("abc").style.setProperty("padding-top", "10px");
document
  .getElementById("abc")
  .style.setProperty("padding-top", "10px", "important");

to select the eleemnt with getElementByid.

And then we call style.setProperty with the property name, value, and optionally, the 'important' string as the 3rd argument.

"important" adds the !important directive.

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.