<!doctype html>
<html>
<head>
<title>Select experiments</title>
<meta charset="UTF-8">
</head>
<body>
<script>
class MyCustomSelect extends HTMLSelectElement {
constructor() {
super();
}
// Intercept calls to set value in order to update the View, then forward to
// HTMLSelectElement base class. Can be done for other view-impacting properties as well.
set value(newValue) {
let li = document.createElement("li");
li.innerText = `set value to ${newValue}`;
document.getElementById("log").append(li);
super.value = newValue;
// Queue update to the View here.
}
// Example of how the derived class can include default light-DOM content to be slotted
// into the custom <select>. Here it's just <option>s but in the future this could
// be the custom <select> UI.
connectedCallback() {
let option0 = document.createElement("option");
let option1 = document.createElement("option");
option0.innerHTML = "This is a default option. A framework could add this.";
option1.innerHTML = "For a custom select a framework could also provide custom UI to be slotted in.";
this.append(option0, option1)
}
// This approach doesn't work for intercepting select.value = 'foo' since this only watches content attributes.
attributeChangedCallback(name, oldValue, newValue) {
console.log(`attributeChangedCallback ${name} set to ${newValue}`);
}
static get observedAttributes() {
return ["value"];
}
}
window.customElements.define("custom-select", MyCustomSelect, { extends: "select" });
function changeSelectValue() {
document.querySelector("select").value = "thing 2";
}
</script>
<select is="custom-select">
<option>thing 1</option>
<option>thing 2</option>
</select>
<input type="button" value="Click to change...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.