Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending an HTML Element

I am using ES5 to make a custom web component that extends HTMLAnchorElement. Since web components only work in ES6 and up I have included the ES5 polyfill located here.

Making a web component that extends HTMLElement and then using its tag on the page works fine. But extending any element other than HTMLElement does not seem to work.

I am using the latest version of Google Chrome to test this.

Below is my code for the element that is extending HTMLAnchorElement.

function CustomAnchor() {
    HTMLAnchorElement.call(this);
}

CustomAnchor.prototype.connectedCallback = function () {
    console.log('anchor added to dom');

    this.addEventListener('click', 
        function(e) {
            console.log('test');
            e.preventDefault();
            var result = confirm('Confirmed!');
        }
    );
};

window.customElements.define('custom-anchor', CustomAnchor, {extends: 'a'});

And here is the code that creates the element and adds it to the DOM:

var el1 = document.createElement("a")
el1.setAttribute("is", "custom-anchor")
el1.setAttribute("href", "http://www.google.com/")
el1.text = "Go to Google"
document.body.appendChild(el1)

And here is what shows up in the DOM, which looks correct:

<a is="custom-anchor" href="http://www.google.com/">Go to Google</a>

No errors are showing up in the console but when the element is appended to the DOM the connectedCallback is never fired.

The link works just like a normal anchor link as if it had never been extended.

What am I doing wrong here?

like image 286
Graham Avatar asked Nov 28 '17 18:11

Graham


1 Answers

As of Nov 28, 2017 extending anything besides HTMLElement is not supported in any browser. The idea of <button is="my-button">Click Me</button> is not supported in Native V1 components.

For more info read the section Extending native HTML elements found here: https://developers.google.com/web/fundamentals/web-components/customelements

it states: "Warning: At time of writing, no browser has implemented customized built-in elements (status). This is unfortunate for accessibility and progressive enhancement. If you think extending native HTML elements is useful, voice your thoughts on Github."

UPDATE 1:

As of May 28 2018 Chrome 67 supports Customized built-in elements And Firefox 63 claims full support too.

Sometime in Sept or Oct 2018 MS started working on their support for Custom Elements and Shadow DOM in Edge. But there is no indication on when it will be finished.

like image 137
Intervalia Avatar answered Oct 16 '22 06:10

Intervalia