(Photo by Anthony Martino on Unsplash)

If you’re looking on the web for a solution to programmatically set the selections of a multiple select element in JavaScript you most likely find answers using jQuery, an indexed loop and an if condition, or some other complicated stuff. Modern browsers and ES6 gives you a simple solution in (almost) a single line of code:

HTML:

<select id="selectElement" size="3" multiple>
<option value="oranges">Oranges</option>
<option value="apples">Apples</option>
<option value="cherries">Cherries</option>
</select>

JavaScript:

let selectElement = document.getElementById('selectElement');
let a = ['oranges', 'cherries'];
for (option of selectElement.options) option.selected =
a.includes(option.value);

There you go!


Photo by Max Bender on Unsplash

Web development is based on free software by developers like you and me, isn’t it? At first glance, this seems to be the case. Let’s take a look at the main tools modern web is mainly developed with nowadays:

  1. Visual Studio Code
  2. TypeScript
  3. React
  4. npm
  5. GitHub
  6. Chrome

Most of the tools are Open Source projects (VS Code only in parts, npm is proprietary). So where are the big companies? Well, all six tools and sites are owned by Big Tech:

  1. Microsoft
  2. Microsoft
  3. Facebook
  4. Microsoft
  5. Microsoft
  6. Google

The tools we use all day rise and fall with the benevolence of companies…


Photo by SLON V KASHE on Unsplash

Recently I came across the problem, that I had to programmatically change a div’s color from red to green. Sounds simple and it’s actually quite simple if you know your JavaScript.

jQuery contains a function called “toggleClass()” that swaps class attributes in and out of an element. I looked for a similar function in ES6 but couldn’t find one. Florian Brinkmann (@FloBrinkmann) pointed me to “classList.toggle()” which does exactly the thing I’m looking for (it’s hidden in the “Examples” passage).

Here’s the simple solution to my problem:

function toggleClass(element, className1, className2) {
element
.classList
.toggle(className1);
element
.classList
.toggle(className2) …

Latz

Long time WordPress Plugin developer. Nowadays I more often code JavaScript frontends and Chrome extensions. Blog: http://www.elektroelch.net/blog

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store