The way the DOM works (which represents an HTML page in memory), text and tags such as <div> are both represented by "nodes" of different types organized in a tree structure so that, for example, text nodes become the "children" of element nodes.

A normalized DOM tree means that there are no empty text nodes or adjacent text nodes. The Node object has a normalize() method that makes sure of this.

Read more

Be careful inside try-catch blocks in Javascript async functions. If you don't use await, an error that's thrown might not stop the execution of subsequent code.

Read more

The innerText property magically converts newline characters to <br> elements. If you want to just set the text content of an element, you should use, well, textContent.

Apparently, the difference is that "innerText is aware of the rendered appearance of the text, while textContent is not."

Read more

You can use a Sinon.JS stub with the callsFake() method, passing it an existing function, to effectively "wrap" the function so that it registers each time you call and with which arguments, but in a way that it also seemingly works the same way as the original function does.

Read more

You can send data with the application/x-www-form-urlencoded content type (the one that encodes values similar to a query string, e.g. first=1&second=2) using a URLSearchParams object, like so:

fetch(url, {
  method: "POST",
  body: new URLSearchParams({first: 1, second: 2})
});
Read more

There's an API in Chrome and Firefox (that I know of) that lets you get localized strings with variable replacements from a JSON file that you provide.

var message = browser.i18n.getMessage("messageContent", target.url);
console.log(message);
Read more

Arrays can be copied using spread syntax, introduced in ES6. To illustrate:

let a = [1, 2, 3];

// This won't work.
let b = a;
b[0] = 99;
console.log(a[0], b[0]); // prints "99 99"

// But this will.
let c = [...a]; // before ES6 there was an even uglier way of doing this using "slice", but let's never talk about that
c[0] = 12345;
console.log(a[0], c[0]); // prints "99 12345"
Read more

There are different types of functions in modern-ish JavaScript: regular, async, and generator functions. However, typeof returns "function" for all of them. One way (the only?) to differentiate between them is by using toString.call(myFunc).

Read more
Subscribe to JavaScript
Mastodon Mastodon