ES6 does not allow the use of native setters when extending the HTMLButtonElement

Looking for a way to utilize the native setters and getters for an extended HTMLButtonElement, particularly focusing on the 'disabled' property.

You can find more information about the property here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement

An example code snippet can be accessed through the following link: http://codepen.io/anon/pen/RWmKaw?editors=001

Highlighted excerpt from the provided link:

'use strict';

class TestButton extends HTMLButtonElement {
  attachedCallback() {
    this.appendChild(document.createTextNode('test'));
    this.addEventListener('click', (event) => {
      this.customFun();
    });
  }

  customFun() {
    alert('setting myself as disabled.');
    this.disabled = true;
  }
}
document.registerElement('test-button', TestButton);

document.body.appendChild(document.createElement('test-button'));

Encountering an error when attempting to access the disabled property during set or get operations:

Uncaught TypeError: Illegal invocation(anonymous function) @ pen.js:33

While overriding the setter and getter for TestButton is possible, it doesn't address the root issue, only treats the symptom.

Alternatively, experimenting with the syntax below has been tried: codepen: http://codepen.io/anon/pen/NGVddj?editors=001

'use strict';

class TestButton {
  attachedCallback() {
    this.appendChild(document.createTextNode('test'));
    this.addEventListener('click', (event) => {
      this.customFun();
    });
  }

  customFun() {
    alert('setting myself as disabled.');
    this.disabled = true;
  }
}
document.registerElement('test-button', {prototype:TestButton, extends:'button'});

let myButton = document.createElement('button', 'test-button');
myButton.setAttribute('is', 'test-button');
myButton.customFun();
document.body.appendChild(myButton);

This attempt led to the removal of custom element functions and triggered the error message:

Uncaught TypeError: myButton.customFun is not a function

Answer №1

After some thorough investigation, I finally cracked the code:

'use strict';

class TestButton extends HTMLButtonElement {
  attachedCallback() {
    this.addEventListener('click', (event) => {
      this.customFun();
    });
  }

  customFun() {
    alert('I am now setting myself as disabled.');
    this.disabled = true;
  }
}
document.registerElement('test-button', {
  prototype: TestButton.prototype,
  extends: 'button'
});

let myButton = document.createElement('button', 'test-button');

document.body.appendChild(myButton);

The real magic lies in extending HTMLButtonElement to inherit properties from its parent elements. Combining this with the right syntax within the register and creation of elements, everything falls into place flawlessly.

Additionally, the key to resolving the issue was the removal of the 'is' attribute.

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

Advantages of using individual CSS files for components in React.js

As someone diving into the world of Web Development, I am currently honing my skills in React.js. I have grasped the concept of creating Components in React and applying styles to them. I'm curious, would separating CSS files for each React Component ...

Tips for concealing a dynamic DOM element using JQuery after it has been generated

My current project involves creating a form that allows users to dynamically add text fields by clicking on an "add option" button. Additionally, they should be able to remove added fields with a "remove option" link that is generated by JQuery along with ...

What is the process for viewing the collections of all databases while logged in as an administrator?

My aim is to display all databases along with their collections, similar to logging in as an admin user into robo3T, for example. Using the two commands below poses no issue. However, when I use the listCollections command, I only get the collections from ...

Ways to handle a hidden element in Selenium Webdriver

Special features of this element:- <textarea id="txtSuffixTitle" class="form-control" tabindex="3" rows="2" placeholder="Suffix Title" name="txtSuffixTitle" maxlength="50" cols="20" style="display: none; visibility: hidden;">Suffix Title </text ...

What could be causing the post method to fail in this AngularJS example?

After successfully reading a JSON file in my sample code, I encountered an issue when trying to update the JSON file. The error message "Failed to load resource: the server responded with a status of 405 (Method Not Allowed)" appeared, even though the data ...

Tips for including a JSON file within the utils directory of a Node.js project

I have a JavaScript file located in the utils folder of my Node.js project. This JS file is responsible for retrieving data from a database. However, at the moment, I only have mock data stored in a local JSON file. Now, I need to figure out how to load th ...

Designing an interactive HTML table that adapts to various screen

Currently utilizing Bootstrap to create a responsive HTML table on smaller devices like the iPad, but seeking a more polished and professional alternative. Searching for a JQuery/JavaScript or CSS solution without relying on plugins. Would appreciate any ...

Is it acceptable to halt the execution of an async route handler in an Express application using a return statement?

My async route handler is set up like this: router.post('/', async function (req, res, next) { try { const { username, email, password } = req.body const { errors, userData } = validateRegistrationInput(username, email, password) if ...

Page resizing is disabled in Chrome after an Ajax load

I've been tirelessly working on the CSS for a website I'm building, and I've encountered a strange issue that only seems to affect Chrome. Firefox and Internet Explorer work perfectly fine. I am using jQuery to load HTML stubs and a signifi ...

Is it possible for me to determine whether a javascript file has been executed?

I am currently working with an express framework on Node.js and I have a requirement to dynamically change the value (increase or decrease) of a variable in my testing module every time the module is executed. Is there a way to determine if the file has ...

Photoswipe using identical source code, yet the output is malfunctioning

Having an issue with my code that refreshes the content of a ul element. Initially, it works fine by directly loading the ul content, but I am constantly creating new content every 10 seconds to provide users with fresh updates. Even though the source co ...

Im testing the creation of a global style using styled-components

Is there a way to create snapshot tests for styled-components with createGlobalStyle? The testing environment includes jest v22.4.4, styled-components v4.1.2, react v16.7, jest-styled-components v5.0.1, and react-test-renderer v16.6.3 Currently, the outp ...

There appears to be an issue with the v-model in the Vuetify v-btn-toggle

I have a situation where I am using two v-btn-toggles with multiple buttons in each. When selecting a button in the first toggle, it should impact which buttons are available in the second toggle based on a specific pattern: firstButtons: [ "a", "b", "c" ] ...

Retrieve a string value in Next.JS without using quotation marks

Using .send rather than .json solved the problem, thank you I have an API in next.js and I need a response without Quote Marks. Currently, the response in the browser includes "value", but I only want value. This is my current endpoint: export ...

What is the best way to structure Vue.js components for optimal organization?

Imagine having an index page called index.vue consisting of various components like this: index.vue <template> <div> <component-1 /> <section class="section-1"> <div class="container section-container"> <com ...

What is the best way to use a JavaScript function as a callback?

I'm struggling with understanding callbacks, especially how they function. Here is my function: function checkDuplicateIndex(values, callback) { $.ajax({ type: "POST", url: url, data: "command=checkIndexAlbumTracks& ...

I'm curious as to why the for-of loop within the function isn't producing the anticipated results that the regular for loop is achieving

Why is the behavior of the for...of loop different from the traditional for loop within this function? It appears that the 'el' in the for...of loop does not behave the same as iterable[i] in the regular for loop? var uniqueInOrder = function(it ...

Trouble with linking an external JavaScript file in HTML document

I'm having some trouble including an external JavaScript file in my HTML. I followed the steps but the pie chart is not showing up as expected. Can someone please take a look and let me know if I missed anything? Here's the link to where I got th ...

Windows authentication login only appears in Chrome after opening the developer tools

My current issue involves a React app that needs to authenticate against a windows auth server. To achieve this, I'm hitting an endpoint to fetch user details with the credentials included in the header. As per my understanding, this should trigger th ...

How can I change the background color of my notification box to red if the count is not equal to zero?

When the count equals 0, I don't want any effect on the notification box. However, when the count is not equal to zero, I want the notification box to turn red. I tried implementing this, but it's not working as expected. By not working, I mean n ...