Adding HTML elements retrieved from an AJAX request to the shadow DOM

I am attempting to create a custom shadow DOM element that retrieves its HTML content from an HTML file located in a components folder. I have successfully retrieved the HTML using the following code:

$.get( "/component/miniPlayer.html", function( data ) {
    console.log(data)
    root.innerHTML = data;
});

However, when I try to insert this HTML into the custom element like so:

class miniPlayer extends HTMLElement{
    constructor(){
        super();

        this._root = this.attachShadow({mode: 'open'});
        this._root.innerHTML = 

        $.get( "/component/miniPlayer.html", function( data ) {
            console.log(data)
            this._root.innerHTML = data;
        });
    }
}

window.customElements.define('mini-player', miniPlayer);

An error occurs stating

Uncaught TypeError: Cannot set property 'innerHTML' of undefined
. Despite trying various configurations, I have been unable to resolve this issue. Is there a solution for this problem, or should I pursue an alternative approach?

Answer №1

This within the function(data) {...} callback of your function does not refer to the same this as in the constructor() due to the concept of closure.

To avoid confusion, it is recommended to store the original reference in a separate variable (for example: that or in this case: elem).

class miniPlayer extends HTMLElement{
    constructor(){
        super();

        this._root = this.attachShadow({mode: 'open'});
        

        var elem = this;
        $.get( "/component/miniPlayer.html", function( data ) {
            console.log(data);
            elem._root.innerHTML = data;
        });
    }
}

window.customElements.define('mini-player', miniPlayer);

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

Is there a way to replicate the functionality of Python's zip() function in JavaScript

Struggling to translate this function into JavaScript... def pascal(n): row = [1] k = [0] for x in range(max(n,0)): print(row) row=[l+r for l,r in zip(row+k,k+row)] return n>=1 I'm encountering difficulties with th ...

retrieve information in the form of an array by making an AJAX request with the

Looking for a solution on how to send an array of strings as data from a PHP file? Check out the code snippet below: function getMods(){ var modsData; $.ajax({ type: "POST", url: "init.php", data: { 'id': getID()} ...

Tracking form submissions on Internet Explorer using a bootstrap modal window - a step-by-step guide

Currently, I have a form that users fill out and submit using jquery with $("form").submit(); During the submission process, I utilize a modal window from the Twitter Bootstrap library to block the screen and inform the user that the form is being process ...

Retrieving detailed data from a JSON document

I'm currently developing an app that requires users to click on a location and then be directed there using Google Maps. I have a vast database of locations stored in JSON format. My goal is for the app to retrieve the coordinates when the user clicks ...

Implementing setDoc with Firebase-Admin using Typescript in Firestore

I'm having issues with my code in config/firebase.ts: import { initializeApp, cert } from 'firebase-admin/app'; import { getFirestore } from 'firebase-admin/firestore' const firebaseAdminApp = initializeApp({ credential: cert( ...

Using a combination of nested fetch() and array.map() does not allow for the return

My previous coding experience didn't present any issues with rendering HTML. Typically, I only needed to use one fetch() function. However, in this particular scenario, it appears that I require two fetch calls. The first fetch retrieves a product ID ...

Instructions for inserting an HTML page into a DIV using a menu LI click event

I have encountered a frustrating issue. My plan is to create a UL menu with varying amounts of LI elements inside. When each LI element is clicked, I want to load a new HTML page into my "Content-DIV". I've done extensive research and discovered Aja ...

Unable to hide the mobile menu button

https://i.sstatic.net/5rdYY.pngI am currently working on a fun website project . I am facing an issue with the mobile menu button not disappearing using display:none in Safari on my iPhone when in landscape mode, even though it works fine in Chrome. My g ...

What is the best way to assign src and alt attributes to an image tag using JavaScript?

As I continue to learn JavaScript, please bear with me as I navigate through my current level of understanding. I am working on a gallery that opens a modal when an image is clicked. I have successfully gathered all the image sources into an array and used ...

Display a loading image as a placeholder while the Block is loading on the Viewport

Despite my extensive search for a solution to my problem, I have been unable to find one that addresses it directly. I am trying to display a "loading" image for 4 seconds before the content of the div is loaded. Unfortunately, I haven't been able to ...

Discrepancy discovered in Bootstrap 5 container dimensions compared to provided documentation

I am currently delving into Bootstrap 5 (I have some experience with coding but not much with web technologies). To better understand how Bootstrap works, I've been creating HTML documents to experiment with its behavior. While working on the "conta ...

Is it possible to hide a portion of a jQuery UI draggable element using display:none while maintaining the cursor position?

My challenge involves having draggable elements with images that need to be dropped into folders. In order to maximize screen space and keep more draggables visible at once, I have decided to hide the images using CSS during the drag operation. However, I ...

Enhance the structure of information retrieved from the API

Recently I sought advice on formatting API data and received some excellent responses. However, I encountered an error when the API lacked data for certain assets: https://i.stack.imgur.com/HgJDd.png Here is an example without the highlighted code: http ...

When you click on links and buttons, a focus outline appears

I am currently troubleshooting an issue within an existing application that relies on the use of jQuery. The problem arises when I click on any link or button on the page, causing the element to display a focus outline (such as a blue glow in browsers like ...

What could be causing the issue of rows being undefined?

Need help creating a user registration feature with Passport(Local-Signup)? Check out the code snippet below: // config/passport.js // requiring necessary modules var LocalStrategy = require('passport-local').Strategy; // loading the user mode ...

Next.js throws an error when trying to access the document object while using React Aria overlays

Recently, I've been diving into Next.js for web development and stumbled upon commerce, a template specifically designed for e-commerce websites using Next.js. While exploring the codebase, I noticed the Sidebar component which leverages React Aria fo ...

Implementing Axios interceptor is a common practice in Vue.js applications to central

Hello everyone, I'm facing a problem with the interceptor in VueJS. I can't seem to figure out where the issue lies and it's driving me crazy... I've gone through various tutorials and read numerous posts on stackoverflow, but everythi ...

Utilize Ajax to automatically populate a textbox with suggestions

I'm retrieving data via an AJAX call. How can I bind the data for auto-completion in a text box using both the name and ID as fields? What is the best way to bind this data in the frontend and retrieve the selected name's ID in the backend using ...

How to calculate average ratings in a collection using Mongoose?

In my NodeJS application with Mongoose, I'm looking to generate responses that display the average ratings from responses to a questionnaire for each question. Here is how my Schema is structured: const questionnaireResultSchema = new Schema({ ...

Bringing in JavaScript files from a Bootstrap theme to incorporate them into a Vue3 application

Incorporating Bootstrap 5, a HTML theme with a CSS bundle file, and separate JS bundle files (main JS bundle file and plugin bundle file) containing Bootstrap code base + custom template features into a Vue 3 project is my current objective. I aim to utili ...