So it's back to relearning the base language and (re)discovering a few handy tricks. Here's five:
- Easy AJAX: fetch(url).then(function(result),function(error))
fetch() is a simple replacement for ajax functionality. It enjoys cross-browser support in a single, easy format and coupled with .then() statements, provide an easy chain of events for retrieving and processing data. The first function inside the .then() clause is only executed once the preceding function completes, but if there was an error, the second function is executed instead. Multiple .then() statements can be chained to create a sequence of events.
- Easy array looping: .map(function) vs .every(function) vs .find(function) vs .findIndex(function)
.map() is a way to execute a function on every item in an array. Importantly, it returns a new array! If you don't need a new array but you want to make sure the function works for every item, consider using .every() instead. The function should test each array value and return true or false. As soon as one of the array items returns false, the whole thing stops and .every() returns false. If all the array items return true, .every() returns true! But suppose you just want to find that one array item who was different, you could use .find() instead. It runs a function on each item in the array until one of them returns true, and then returns that item. If you just need the array index of that item, use .findIndex() instead.
- Easy HTML class attributes: .classList with .add(strings) or .remove(strings) or just .toggle(string,test) or .replace(old,new) and .contains(string)
.classList is an easy way to access the classes on an HTML element. Multiple classes can be added or removed using .add() or .remove() and it's safe to specify a class that may or may not be present. Regardless, the existence of a class can be checked using .contains() and a class can be replaced using the .replace() method. But why decide when to replace when you can just toggle using the .toggle() method! It has an optional true/false second argument if you really want to decide.
- Easy form values: FormData(form) and .checkValidity() with .get(name) and .set(name,value) as well as .keys() and .values()
- Easy HTML element search: .contains(element) or .querySelector(string) or .querySelectorAll(string)
.contains() is an easy way to determine if an HTML element is inside a parent/ancestor element. It just returns true or false. If you want to find specific elements, use .querySelectorAll() as a replacement for .getElementById, .getElementsByClassName, .getElementsByTagName, and .getElementsByName! It's the same as jQuery's $('node, #id or .class') lookup and supports pretty much all CSS selectors. If you just need the first match, simplify with .querySelector().
Well that's it for now, hopefully there was a few fresh bananas in there to help you swing through your projects! And if I've missed anything, feel free to fling them into the comments below.