An error has occurred in the Shadow Dom due to the inability to access the property 'style' of an

While working on a component using shadow DOM, I encountered the following error in the console: "Cannot read property 'style' of undefined". This issue seems to be related to my HTML code in PHP. The main challenge I am facing is figuring out how to execute the JavaScript code responsible for enabling the image slideshow functionality. Interestingly, when I include an alert in the script, it successfully runs, indicating that the code is functional. However, I am unable to access the style property.


html
<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <title>Avisos</title>        
    </head>

    <body>
        <aviso-dos>A</aviso-dos>
        <aviso-dos>B</aviso-dos>
        <aviso-dos>C</aviso-dos>

        <template id="plantilla">
            <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

            <style>
                .item {
                    width: 288px;
                    height: 192px;
                    border-style: solid;
                    border-width: 1px;
                    border-color: DarkGray;
                }

                #iconos{ 
                    display: none;
                }

                #aviso:hover #iconos{
                    display : block;
                    background:rgba(255, 255, 255, 0.75);
                }      

                .slide {
                    display: none;
                }
            </style>

            <div id="aviso" class="item w3-display-container">
                <div id="iconos" class="w3-display-middle w3-display-container w3-animate-opacity" style="width:100%; height:100%">
                    <!-- Add your image and icon elements here -->
                </div>
                
                <!-- Add your slideshow images here -->
            </div>

            <script>
                // Add your slideshow script here
            </script>
        </template>

        <script src="aviso2.js"></script>
    </body>
</html>

AND THIS IS MY JAVASCRIPT
My problem is that I don't know how to get the JavaScript code that gives the image slideshow functionality to run.
If I put an alert in the script it runs, so the code runs.
But I can't access the style property.


class aviso2 extends HTMLElement {
    
    constructor() {
        // Always call super first in the constructor
        super();

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

        this.template = document.getElementById("plantilla");

        this.shadowRoot.appendChild(this.template.content.cloneNode(true));
    }

    connectedCallback(){
        // Implement any additional logic here
    }
}

customElements.define('aviso-dos', aviso2);

Answer №1

Executing the line

x[myIndex-1].style.display = "block";
results in x.length being equal to 0 because the nodes have not yet been created in the DOM.

To tackle this issue, consider adding the carousel script after the custom element has been created:

customScript.js

 window.customElements.define("custom-element-name", customScript);

 const additionalScript = document.createElement("script");
 additionalScript.src = "carousel.js";
 document.body.appendChild(additionalScript);

Answer №2

After extensive research across various forums, I finally managed to uncover the solution by gathering information from different sources. I trust that this discovery will prove beneficial for you in the future.

class notification2 extends HTMLElement { 
constructor() {
    super();
    
    this.attachShadow({mode: 'open'});

    const template = document.getElementById("template");

    this.shadowRoot.appendChild(template.content.cloneNode(true));

    this.currentIndex = 0;
    this.slides = this.shadowRoot.querySelectorAll(".slide");
}

test()
{
    this.test2();
}

test2(){
    var index;
    
    for (index = 0; index < this.slides.length; index++) {
        this.slides[index].style.display = "none";  
    }

    this.currentIndex++;

    if (this.currentIndex > this.slides.length) {
        this.currentIndex = 1
    }    

    this.slides[this.currentIndex-1].style.display = "block";  

    setTimeout(() => {
        this.test2();
    }, this.getAttribute('time'));
}

connectedCallback() {
    this.test();
}

}

window.customElements.define('notification-two', notification2);

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

The jspdf function is not displaying any images in the PDF file

I am new to coding and encountered an issue when trying to download images in reactjs. After clicking the download button, I only receive a blank pdf file. https://i.stack.imgur.com/0XJcC.png The function in my react code that attempts to generate the p ...

jQuery UI Tabs - The initial slide is not being displayed automatically

My default setting for the first tab is .ui-tabs-hide, causing it to be hidden along with all other tabs. Here's my code snippet: <script> $(document).ready(function(){ $("#slide-container").tabs({ fx: { opacity: 'toggle' ...

Display a hidden form field in Rails depending on the object's value

As a programmer learning Ruby on Rails without much knowledge of Javascript, I faced a problem with a form that creates an object called Unit. This Unit model is related to Category which in turn is related to Product. The issue was that while selecting a ...

The function element.innerHTML is invalid when trying to assign an object value as an option

Hey there! I'm currently working on a JavaScript project where I have an input that retrieves text from an array. Each option in the array needs to be linked to an object so I can utilize its attributes. const data = [ { name: "SIMPLES NACION ...

Having trouble with implementing the Drag API Function alongside Javascript Arrow Functions?

I've searched extensively for a similar question but couldn't find one, so I hope this is not a duplicate. Recently, I created a factory function to assist me with drag and drop functionality in my current project. However, I noticed varied beha ...

How to access variables with dynamic names in Vue.js

I'm curious if it's possible to dynamically access variables from Vue’s data collection by specifying the variable name through another variable. For instance, consider the following example: Here are some of the variables/properties: var sit ...

Updating parent data in Vue.js does not automatically trigger an update in the child component

I have the following: Vue.component('times-updated', { template: '<span>Times Updated: {{ timesUpdated }}</span>', data: function() { return { timesUpdated: this.$parent.myData.timesUpdated ...

The NUXT project encounters issues when trying to compile

I am currently working on an admin panel using the nuxt + nest stack. I am utilizing a template provided at this link: https://github.com/stephsalou/nuxt-nest-template While in development mode, the project starts up without any issues. However, when I ...

What causes the picturesArray to remain consistently void?

const fetch = require("node-fetch"); let images = []; fetch('http://www.vorohome.com//images/assets/159314_887955.png') .then(response => response.buffer()) .then(buffer => { const data = "data:" + response.headers.get ...

Is it possible to have one div layer on top of another?

On my website, I have a line of text that is revealed when a dropdown arrow is clicked. However, there are certain pages where the divs extend beyond this single line of hidden text. For example: https://i.sstatic.net/2a6YB.png I need the green div (nor ...

What is the procedure to change a matter body's isStatic property to false in matter.js upon pressing a key?

During my recent project, I encountered a challenge in trying to set the isStatic property of a Matter Body in matter.js to false when a key is pressed. if (keyIsPressed(UP_ARROW)) { this.body.isStatic(false) } Could you provide guidance on the correct ...

Tips for Ensuring a JavaScript Contact Form Submits Successfully

Snippet of HTML Code for Contact Form: Contact Me <label for="Name">Name:</label> <input type="text" name="name" id="Name" accesskey="N" tabindex="1"> ...

HMR: The webpack-hot-middleware is not refreshing my webpage

My Vue application, titled hello-world, is utilizing webpack-dev-middleware and webpack-hot-middleware. When running the application, it shows that it's connected in the console. However, after making changes to my main.js file, the following message ...

Using Python and Selenium to manipulate the webpage and execute JavaScript can help reconstruct the true HTML structure

I have a very basic Selenium code snippet that I am running: <input name="X" id="unique" value="" type="text"> <script> document.getElementById("unique").value="123"; </script> While I can retrieve the input value "123" using driv ...

Replacing text with new content when text is stored in a separate file

After organizing all the strings from my code, I compiled them into a file named constants.ts. export class Constants { public static API_URL = '/api/'; public static CREATE_CHILD_API_URL = Constants.API_URL + '%s' + '/create- ...

"Exploring the world of jest.doMock: A guide to mocking

Here is the code snippet I am testing: ... import data from '../data/mock.json'; // function is async export const something = async () => { try { ... if (!data) { throw 'error is here!'; } ...

Steps to align table next to the paragraph tag

I am facing an issue trying to align a table inline with the p tag in my HTML code. I have attempted to make minimal changes to achieve this, but it is not working as expected. Here is the code I have tried: <p>ABCD</p> <table style = displ ...

Pattern for identifying JavaScript import declarations

My task involves using node to read the contents of a file. Specifically, I am looking to identify and extract a particular import statement within the file that includes the "foo-bar" package. The goal is to match only the line or lines that contain the ...

Determining the nearest upcoming date from a JSON dataset

Looking to find the nearest date to today from the array "dates". For example, if today is 2011-09-10 -> the next closest date from the JSON file is "2012-12-20" -> $('div').append('date1: ' + dates.date1); For example 2, if tod ...

Turn off choices by utilizing data type attribute values within select2 version 4

I'm attempting to deactivate the options by using the data-type attribute specified for each option in select2. Unfortunately, my attempts have been unsuccessful thus far. In addition, I am encountering this error within the change event handler: ...