What is the interaction between custom HTML tags and cloning a template in web development?

I'm feeling stuck with this particular test case. In the ending part of the html code, I have:

<template id="test">
    <test-tag class="test-id"></test-tag>
</template>

Within the script:

class TestTag extends HTMLElement {
    constructor() {
        super();
        console.log("TestTag created");
    }
    get Property() : string {
        return "Hello";
    }
}

// inside a function:
    customElements.define("test-tag", TestTag);
    customElements.whenDefined("test-tag").then(() => {
        console.log("test-tag defined");
        var tag = document.createElement("test-tag") as TestTag;
        console.log(tag.Property);

        var template = document.getElementById("test") as HTMLTemplateElement;
        var clone = template.content.cloneNode(true) as DocumentFragment;
        var tag2 = clone.querySelector<TestTag>(".test-id");
        if(tag2 == null){
            console.error("tag2 is null");
        } else {
            //customElements.upgrade(tag2);
            if(!(tag2 instanceof TestTag)){
                console.error("WTF?!"); //did not expect to be here
            }
            console.log(tag2.Property); //tag2.Property is undefined
        }
    });

The first instance of tag behaves exactly how I wanted it to. However, the second one is not cooperating: it seems like when cloning the template, it creates a generic DOM element instead of an actual instance of my TestTag class.

In my understanding, the main purpose of custom elements is to define specific behavior and reuse it while designing complex divs using HTML markup rather than messy code involving multiple createElement/appendChild calls. So it appears that I might be overlooking something obvious here. Could it possibly be related to the shadow DOM mechanism or maybe customElements.upgrade() isn't working in this scenario?

My question boils down to this: if there's a key aspect of utilizing custom elements efficiently that has slipped past me, please enlighten me on it. If not, what steps can I take to ensure that the tag2 value in the given example truly represents a TestTag instance, and why does the current behavior occur in such a manner?

Answer №1

Understanding the distinction between a Class Object and a DOM Element connected to the DOM is crucial.

<template id="example">
  <example-tag class="example-id"></example-tag>
</template>

<script>
  class ExampleTag extends HTMLElement {
    get Attribute() {
      return "Hi";
    }
  }

  customElements.define("example-tag", ExampleTag);
  var test = document.createElement("example-tag");
  var templateExample = document.getElementById("example");
  var cloneExample = templateExample.content.cloneNode(true);
  var test2 = cloneExample.querySelector(".example-id");
  console.log(test2.nodeName, test2.constructor.name, test2 instanceof HTMLElement, test2 instanceof ExampleTag, test2.Attribute);

  document.body.append(test2); // TRANSFORM IT INTO A DOM ELEMENT!!!
  console.log(test2.nodeName, test2.constructor.name, test2 instanceof HTMLElement, test2 instanceof ExampleTag, test2.Attribute);

</script>

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

Displaying and Concealing Table Rows using Javascript

I am working with an array of prices that are being displayed in a table using a foreach loop. The goal is to hide specific rows in the table based on certain conditions. The $status variable is set to "YES" if the price is => 30, and "NO" if the price ...

Encountering an error while attempting to map a collection in React JS - the value is

Within my state, I have a collection set up like this: getInitialState: function() { return { studentId: 666, activeTabId: 1, sections: [ {name: 'were', value: 1, label: 'Basic Details'}, {na ...

Issues rendering ThreeJS geometry data imported from Json file

Having been a dedicated user of this website for some time now, I must admit that this is the first instance where I find myself in need of posting a question. The issue at hand revolves around a Json file from which I extract data and manipulate it with m ...

Having trouble with the functionality of a Chrome extension content-script JavaScript that is set to run at document_end

Currently, I am in the process of developing a Google Chrome extension that is designed to hide the "news" section located on the right-hand side of Facebook, along with the ads displayed on the right side. Additionally, the background color is meant to be ...

Debugging on the server side of Meteor application is crucial for

I am attempting to debug a Meteor app on Windows using node-inspector. I am following these steps: First, install node-inspector by running: npm install -g node-inspector Next, start Meteor in debug mode by running: NODE_OPTIONS='--debug' meteo ...

Closing WebSocket connection after sending data

I came across an interesting blog post titled Experimenting with Node.js and decided to try setting it up on my own using the author's provided gist. Unfortunately, I encountered some issues. After further investigation, I discovered that even though ...

Error: The call stack has reached the maximum size limit in nodejs and reactjs

When I attempt to submit the token received from my registration using the code snippet below, I encounter an error stating "maximum call stack exceeded." exports.activationController = (req, res) => { const { token } = req.body; exports.activation ...

Execute a series of repetitive HTTP GET requests and remain patient for all of them to complete

I am working with a REST service that provides a list of 'Json' objects, where each object may contain a link to another resource of the same class. To fetch all these resources recursively starting from a specific one, I have written the followi ...

Dynamic scrolling text for overflowing text display

Here's a scenario I'm facing: Let's say I have three div tags, each 100 pixels wide: <--- DIV WIDTH ---> Text in div 1 Text in div two, it overflows Text in div three <--- DIV WIDTH ---> Currently, I've set the following C ...

Is the "json_encode" function dropping the '+' character when using "json.parse"?

Seeking Assistance I have a question regarding the functionality of php function json_encode and js JSON.parse. I seem to be encountering an issue where the '+' character is being dropped somewhere in the process, particularly when dealing with ...

What is preventing me from implementing my JavaScript event on my EJS code?

Looking to add a click event to the image in my EJS file, here's the EJS code snippet: <div class="container" id="comments"> <div class="row"> <div class="col-lg-12"> <div class="well"> ...

ng-grid automatically resizing columns based on content width

I am currently utilizing AngularJS ng-grid and endeavoring to accomplish the following tasks: 1. Adjust column width dynamically based on the content within each column. 2. Automatically resize the last column to fill the remaining space when hiding column ...

Utilize PHP drop down menus for efficient data sorting and retrieval

On my website, there are two drop-down menus - one for courses and the other for students. I am trying to set it up so that when a course is selected from the first menu, only the students enrolled in that specific course will appear in the second dropdown ...

Customizing React component properties within a Styled Component

I have been experimenting with styled components to customize the appearance of basic material-ui React components. My goal is to pass props into the MUI component and then use styled components to apply CSS styling. One interesting aspect is being able t ...

Change the text of a button by using an input field

How can I dynamically update button text based on input field value? <input class="paymentinput w-input" type="tel" placeholder="0" id="amount-field"> <button id="rzp-button1" class="paynowbutton w-button">Pay Now</button> I want the bu ...

How can I effectively update my Vue.js component for optimal performance?

I have a search page with a text box and search button. I implemented a facet using Vue.js. Initially, everything works fine when I search for something. However, after typing a new text and searching again, the facet does not update with the new values. ...

Stopping the PanResponder in React Native temporarily: A guide

Here is the snippet to create an instance of the panResponder: constructor( props ) { super( props ); this.position = new Animated.ValueXY(); this.panResponder = PanResponder.create( { onStartShouldSetPanResponder: ( ) => true, ...

How to retrieve a MySQL column in Node.js using template literals

I have been trying to retrieve a field from MySQL in my Node.js file using template literals, but I am struggling to get the value. In my post.controller.js file, you can see where it says message: Post ${body.post_id} was successfully created, with post_i ...

What causes a useState to revert back to false when navigating back and forth on the screen?

Recently, I've been working on a feature to toggle favorite products and store their unique id along with an isFav property on a Firebase database. This data is then used to display the favorites on the FavoritesScreen. While testing this functionali ...

Adjust the size of the input field as text is being typed in

Can a text input box be automatically resized as text is entered? I've been looking online but haven't come across any solutions. ...