Javascript: Insert a class declaration post loading of the page

When working with native web components, it is necessary to be able to add class definitions after the page has loaded, especially when new types of components are dynamically added to the DOM.


EDIT: Here's a brief explanation:

In order to define web components, you use a class like this:

customElements.define('my-new-tag', myNewtagClass);
;

Therefore, if you want to introduce a new type of component into the DOM, its corresponding class must be defined. It seems that you cannot programmatically define a global class, as it needs to be defined within the root document/scope.


As of now, the only Pure JavaScript solution I could find is to create the class as a string and insert it using a script in the head of the document.

However, this means having to write the class in this format:

let myClassString = `
class myClass {
  ....
}`;
const sc = document.createElement('script');
sc.setAttribute('type', 'text/javascript');
sc.innerHTML = myClassString;
window.document.head.appendChild(sc);

Unfortunately, this method isn't very practical in most IDEs...

Is there a way to automate this process during the build (considering I use TypeScript and webpack)?

For instance, can I extract the class from a file where it's normally defined and utilize it as a variable elsewhere?

Answer №1

I am perplexed by the intention behind creating a class with a string

Below is some code I extracted from my components;
dynamically generating classes/methods/Web Components

<script>
  console.clear();
  const createElement = (tag, props) => Object.assign(document.createElement(tag), props);
  class BaseClass extends HTMLElement {
    constructor(name = null) {
      super();
      this.name = name;
    }
    connectedCallback() {
      this.hello();
    }
  }
  const createClass = (extendFrom, ...args) => {
    class Klass extends extendFrom {
      constructor() {
        super(...args);
      }
    }
    Object.assign(Klass.prototype, {
      ["hello"] : function() {
        this.innerHTML = `Hello from <b>${this.name}!</b><br>`;
      }    
    });
    return Klass
  }
  const createComponent = (name, defaultClass = BaseClass) => {
    customElements.define(name, createClass(defaultClass, name));
    document.body.append(createElement(name, {
      title: name,
    }))
  }
  document.onclick = () => {
    let count = document.body.querySelectorAll("[title]").length + 1;
    createComponent("new-component" + count);
  }
  createComponent("my-comp1");
  createComponent("my-comp2");
</script>
click document!<br>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the magic of obtaining a random element in Vue.js

I have 3 captivating hero images along with their unique content, and I am looking to showcase them randomly to users each time they refresh the page! My challenge lies in efficiently loading these large hero images using jQuery. Currently, all three imag ...

What is the best way to create a distinct key for the key prop in my map function within a React component?

This is the initial code I have: class Board extends Component { static defaultProps = { nrows: 5, ncols: 5, chanceLightStartsOn: 0.25 }; constructor(props) { super(props); this.state = { hasWon: false, board: this. ...

Automatically trigger the expansion of all panels within Vuetify using code

I'm attempting to use Vuetify 2.3.5 to programmatically control the opening and closing of expansion panels. <v-expansion-panels accordion> <v-expansion-panel v-for="(item,i) in faqs" :key="i"> <div class ...

Exclusive Modal Pop-Up for First-Time Visitors - Utilizing Bootstrap, PHP, and JavaScript

Seeking assistance from the community as I have exhausted my online research efforts. I am currently working on implementing a welcome bootstrap modal in a php environment. Despite being new to php and js, I have managed to make it pop up only once using ...

Pause the counter based on the data attribute containing multiple values

I have a collection of div elements, each with a unique data-attribute value. My goal is to display these values in the divs using JavaScript by incrementing a counter. const numbers = document.querySelectorAll(".number"); console.log(numbers); let c ...

Guide on transferring Vue form input data to Adonis controller through an http request

I have a Vue component that prompts the user to enter their email address. I've utilized v-model for data binding. <template> <input v-model="email" type="text" placeholder="Email" /> <button class="tiny">Send</button> ...

Achieving secure HTTPS connection with socket.io

At the moment, my setup involves: let connectTo = "http://myip:myport"; var socket = io.connect(connectTo, {secure: true}); on the client side and const port = myport; const io = require('socket.io')(port); on the server side. I am looking to ...

Navigate to a specific element using Selenium WebDriver in Java

Currently, I am utilizing Selenium along with Java and ChromeDriver to execute a few scripts on a website. My goal is to scroll the driver or the page to a specific element positioned on the webpage. It is important that this element is visible. I am awa ...

How to Use Jquery to Perform Subtraction on Elements

Hello everyone! I am currently working on creating a nutrition label similar to this one: Example I have set up my database and now I am focusing on getting it to work with one element before moving on to the rest. Here is what my database looks like: in ...

When a textarea contains a new line, it will automatically add an additional row and expand the size of the textarea

Developed a form with the functionality to move placeholders in a textarea upwards when clicked. The goal is to increment the height of the textarea by 1 row for every line break. However, I am uncertain about what to include in the if statement of my Ja ...

Determine the dropdown list value by analyzing the final two variables in a textfield

In my textfield, car registration numbers are meant to be entered. These registrations are based on years in the format GT 74454 12, with the last two digits "12" representing the year 2012. I am looking for a script that can automatically detect the last ...

Guide to building a react-redux application with a Node server as the backend

Hey there! I'm looking to build a react-redux app with a node server as the backend. Is it feasible for the node server to serve the react-redux app instead of having react-redux run on one port and node on another? Any suggestions on how to kick thi ...

Unable to dynamically load a component into page.tsx within Next.js

When importing a component into another component there are no issues, but when trying to import a component into a page it results in an error... I am new to this so any help is greatly appreciated. This is how I am importing: const CodeSampleModal = dy ...

Arranging an array containing three elements

As I work on my angular app, I have come across the following array: [ { "Name": "Jack", "IncomingTime": "2020-06-19T11:02+00:00", "Outgoingtime": "2020-06-19T11:07+00:00" ...

Stop the Sidebar from showing up on certain pages with Next.js

Currently, I am facing a small issue with my application. The problem lies in the sidebar that appears on my login.jsx page when I specifically do not want it there. However, I would like it to appear on all other pages except for this one. Is there a cond ...

Why does the value of my input get erased when I add a new child element?

I seem to be facing an issue when I try to add an element inside a div. All the values from my inputs, including selected options, get cleared. Here's a visual representation of the problem: When I click the "Add Key" button, the text in the textbox ...

Utilizing jQuery to implement a function on every individual row within a table

I have a collection of objects that requires applying a function to each item, along with logging the corresponding name and id. Below is the snippet of my code: var userJson = [ { id: 1, name: "Jon", age: 20 }, { ...

A step-by-step guide on transferring Data URI from canvas to Google Sheet using the fetch method

I am trying to send an image as base64 code to a Google sheet using fetch. However, I am encountering an error that says "data_sent is not defined" when I run my code. I need help identifying the problem and finding a solution to fix it. For reference, & ...

What are the possible reasons for a checkbox not being checked in React JS?

I've been working with react final form and I'm encountering an issue where I can't seem to get the checkbox to be properly checked. I'm not sure what mistake I might be making. Take a look at my code on CodeSandbox const AppWithIconTo ...

Avoid positioning issues when dropping a DIV onto the Canvas

Utilizing the JavaScript code below allows me to drag a DIV onto a canvas. I am currently loading a multi-page PDF, which consists of image files, in a pop-up window and positioning canvas layers over them. In these canvas layers, shapes are then loaded at ...