Skip to content

Instantly share code, notes, and snippets.

@cursorial
Created June 3, 2024 12:53
Show Gist options
  • Save cursorial/6a98972450529643894aac06333909d3 to your computer and use it in GitHub Desktop.
Save cursorial/6a98972450529643894aac06333909d3 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SQL DOM Manipulation</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.6.2/sql-wasm.js"></script>
<style id="dynamic-styles"></style>
</head>
<body>
<div id="app">
<div class="example" data-id="1">Hello World</div>
<div class="example" data-id="2">Another Element</div>
</div>
<script>
async function initSqlJs() {
const SQL = await initSqlJs();
const db = new SQL.Database();
return db;
}
async function main() {
const db = await initSqlJs();
// Create table to represent the DOM
db.run("CREATE TABLE dom (id INTEGER PRIMARY KEY, selector TEXT, attribute TEXT, value TEXT);");
// Insert initial state of the DOM
db.run("INSERT INTO dom (id, selector, attribute, value) VALUES (1, '.example[data-id=\"1\"]', 'innerText', 'Hello World');");
db.run("INSERT INTO dom (id, selector, attribute, value) VALUES (2, '.example[data-id=\"2\"]', 'innerText', 'Another Element');");
function syncDom(db) {
const res = db.exec("SELECT * FROM dom;");
res[0].values.forEach(row => {
const [id, selector, attribute, value] = row;
const element = document.querySelector(selector);
if (element) {
if (attribute === 'innerText') {
element.innerText = value;
} else {
element.style[attribute] = value;
}
}
});
}
// Function to execute SQL and sync the DOM
function executeSql(sql) {
db.run(sql);
syncDom(db);
}
// Example: Change the text of the first element
executeSql("UPDATE dom SET value = 'Hello SQL World' WHERE id = 1;");
// Example: Change the color of the second element
executeSql("INSERT INTO dom (id, selector, attribute, value) VALUES (3, '.example[data-id=\"2\"]', 'color', 'red');");
// Sync DOM initially
syncDom(db);
}
main();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment