Can anyone help me to understand why this layout is being rendered?
customElements.define(
"my-resume",
class myresume extends HTMLElement {
constructor() {
super();
let h1 = document.createElement("h1");
h1.textContent="My Resume Name";
this.appendChild(h1);
}
}
);
customElements.define(
"job-experience",
class jobexperience extends HTMLElement {
constructor() {
super();
let h1 = document.createElement("h1");
h1.textContent="Job Experience";
this.appendChild(h1);
}
}
);
customElements.define(
"company-name",
class extends HTMLElement {
constructor() {
super();
let div = document.createElement("div");
div.textContent = this.getAttribute("name");
this.appendChild(div);
}
}
);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My Resume Template</title>
<script src="myresume.js" defer></script>
<link rel="stylesheet" href="myresume.css" />
</head>
<body>
<my-resume>
<job-experience>
<company-name name="The Last Company Worked"></company-name>
</job-experience>
</my-resume>
</body>
</html>
The element view:
I can understand why the entire layout is reverse that of the HTML mark up. If for example I move the H1 elements up to the top of the parent container things are better. But I don't understand why each new custom element acts like a stack (each new element is pushed on the top) the last element added is always on rendered above other elements.
Custom Element creation logic determines the order of creation. It starts at each parent element and works its way down. But append child reverses the order because the browser will always render the last child appended first.
As mentioned by Patric Evans, your layout is rendering that way because you are using [appendChild] which inserts your node after the last child. If you use [prepend] your layout will render the way you expect.
As mentioned by Danny Engleman, don't do DOM manipulation in the constructor.
I believe this is more like what you are wanting..
customElements.define(
"my-resume",
class myresume extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
let h1 = document.createElement("h1");
h1.textContent="My Resume Name";
this.prepend(h1);
// this.appendChild(h1);
}
}
);
customElements.define(
"job-experience",
class jobexperience extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
let h1 = document.createElement("h1");
h1.textContent="Job Experience";
// this.appendChild(h1);
this.prepend(h1);
}
}
);
customElements.define(
"company-name",
class extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
let div = document.createElement("div");
div.textContent = this.getAttribute("name");
// this.appendChild(div);
this.prepend(div);
}
}
);
<my-resume>
<job-experience>
<company-name name="The Last Company Worked"></company-name>
</job-experience>
</my-resume>
Related
Below ake-class2 inherits from/extends ake-class1.
Adding <select> element to ake-class2.shadowRoot.
console.log this.clickme button to make sure it's inherited correctly.
clickme button doesn't work without adding again lines after comment These 3 lines in ake-class2.
I couldn't understand why this behavior happen.
why this happpens ?
<html>
<head>
<title>AKE Front</title>
<script>
class1_html = `
<div class="container">
<button class="clickme">Click Me</button>
</div>
`
class2_html = `
<select></select>
`
/*--------------------------------------------------------------------------------*/
class AKEclass1 extends HTMLElement { //custom-component class
constructor() {
super(); // always call super() first in the constructor.
//const root = this.createShadowRoot(); //chrome only - deprecated
const root = this.attachShadow({mode: 'open'}); //By calling attachShadow with mode: 'open', we are telling our element to save a reference to the shadow root on the element.shadowRoot property
this.shadowRoot.innerHTML = class1_html;
// These 3 lines
this.container = this.shadowRoot.querySelector("div.container");
this.clickme = this.container.querySelector("button.clickme");
this.clickme.addEventListener("click", this.clickMe.bind(this));
}
clickMe() {
alert("Hello !");
}
}
customElements.define('ake-class1', AKEclass1);
/*--------------------------------------------------------------------------------*/
class AKEclass2 extends AKEclass1 { //custom-component class
constructor() {
super(); // always call super() first in the constructor.
this.shadowRoot.innerHTML += class2_html;
// These 3 lines
//this.container = this.shadowRoot.querySelector("div.container");
//this.clickme = this.container.querySelector("button.clickme");
//this.clickme.addEventListener("click", this.clickMe.bind(this));
}
}
customElements.define('ake-class2', AKEclass2);
/*--------------------------------------------------------------------------------*/
</script>
</head>
<body>
<ake-class2 class="ake_window"></ake-class2>
</body>
</html>
As mentioned in the comments .innerHTML += is the culprit.
What it does:
Create a NEW string by concatening .innerHTML + NEWString
delete the innerHTML DOM tree
and then Garbage Collection (GC) kicks in:
Delete all existing DOM elements, thus remove all connected listeners
set the NEW String as innerHTML
Some 'gurus' say this makes innerHTML evil, I say you need to understand what it does.
In the SO snippet below you see the listener being connected twice, but only executed once when clicked
<script>
class BaseClass extends HTMLElement {
constructor() {
super().attachShadow({mode:'open'})
.innerHTML = `<button>Click ${this.nodeName}</button>`;
this.listen();// but removed by GC
}
listen(){
console.log("add listener on", this.nodeName);
this.shadowRoot
.querySelector("button")
.onclick = (evt) => this.clicked(evt);
}
clicked(evt){
console.log("clicked", this.nodeName)
}
}
//customElements.define('element-1', BaseClass);
customElements.define('element-2', class extends BaseClass {
connectedCallback(){
this.shadowRoot.innerHTML += ` with concatenated HTML`;
this.listen();
}
});
</script>
<element-2></element-2>
Notes:
Using the inline onclick handler, it only allows for one handler where addEventListener can add more (you can use it here if you like)
No need for oldskool .bind(this) by defining lexical scope with a arrow function, not a function reference
all can be chained because
super() sets AND returns the this scope
attachShadow sets AND returns this.shadowRoot
Trying to create some Javascript classes and parent classes, and not sure if I'm doing this correctly, but super() in the child class isn't working as it should. Trying to get content in DivElement to work, but it keeps returning undefined.
Code:
class HTMLElement{
constructor(tag, content){
this.tag = tag;
this.content = content;
}
render(){
return `<${this.tag}>${this.content}</${this.tag}>`;
}
class DivElement extends HTMLElement{
constructor(content){
super(content);
this.tag = 'div';
}
}
let div1 = new DivElement('test');
console.log(div1);
console.log(div1.render());
The super call should match the signature of the target method. It should read super('div', content);:
class HTMLElement{
constructor(tag, content){
this.tag = tag;
this.content = content;
}
render(){
return `<${this.tag}>${this.content}</${this.tag}>`;
}
}
class DivElement extends HTMLElement{
constructor(content){
super('div', content); // changed here
this.tag = 'div';
}
}
let div1 = new DivElement('test');
console.log(div1);
console.log(div1.render());
// <div>test</div>
The constructor of the HTMLElement class is called with two parameters (tag & content). The extended class calls the constructor with only one parameter and assigns content to the tag parameter of the parent class. Note that JS does not allow constructor overloading.
See the answer of Glycerine.
I have created a vanilla web component or HTML element. It just displays two links.
To encapsulate the thing, I use shadow DOM. However it does not seem to be encapsulated. In the DOM tree it's inside #shadow-root which is good.
Why does the web component use the global style instead of the style I provided in the template for my web component?
The text is red and I expected it to be green.
class MyEl extends HTMLElement {
constructor() {
super();
this.shadow = this.attachShadow({ mode: "open" });
}
connectedCallback() {
const template = `
<style>
a {
color: green;
}
</style>
<slot></slot>`;
this.shadow.innerHTML = template;
}
}
window.customElements.define("my-el", MyEl);
a {
color: red
}
<my-el>
Item1
Item2
</my-el>
While this question already has an accepted answer, moving a slot's children to the shadowRoot isn't desirable for most use cases.
What you probably want to do is to use the ::slotted() selector.
Just bear in mind that styles applied to a slot's children through the ::slotted() selector only act as "default" styles and can still be overridden by using styles in light DOM.
For example, check this edited version of your snippet:
As you can see, this time my-el tries to apply both a color and a text-decoration style to anchor (<a>) children in any of it's slots.
However, in light dom, we have a a.special selector that overrides the color, so the <a class="special"> will be red, not green
class MyEl extends HTMLElement {
constructor() {
super();
this.shadow = this.attachShadow({ mode: "open" });
}
connectedCallback() {
const template = `
<style>
::slotted(a) {
color: green;
text-decoration: none;
}
</style>
<slot></slot>`;
this.shadow.innerHTML = template;
}
}
window.customElements.define("my-el", MyEl);
a.special {
color: red
}
<my-el>
Item1
<a class="special" href="example.com">Item2</a>
</my-el>
The full, detailed explanation is in: ::slotted CSS selector for nested children in shadowDOM slot
TL;DR
Your links are in lightDOM and thus styled by its DOM (in your code the document DOM)
Moving the nodes from lightDOM to shadowDOM is one "solution"; but you are not using slots then.
FYI, your code can be compacted to:
class MyEl extends HTMLElement {
constructor() {
super().attachShadow({ mode: "open" })
.innerHTML = `<style>a{color:green}</style><slot></slot>`;
}
}
window.customElements.define("my-el", MyEl);
More SLOT related answers can be found with StackOverflow Search: Custom Elements SLOTs
observe this line, you have to move/copy elements to shadow for example with:
this.shadow.innerHTML = this.innerHTML + template;
I've added this to demonstrate that only inline style will be applied to shadow dom elements .. so copied links in SD are using your style :)
so red will be GLOBAL, green will be SHADOW elements
class MyEl extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.shadow = this.attachShadow({ mode: "open" });
const template = `
<style>
a {
color: green;
}
</style>
<slot></slot>`;
this.shadow.innerHTML = this.innerHTML + template;
}
}
window.customElements.define("my-el", MyEl);
a {
color: red
}
<my-el>
Item1
Item2
</my-el>
For an application i want to create Object-Based components in ES6.
On the normal way, you can create Elements as follow:
var element = document.createElement('YourElement');
element.innerHTML = 'Content';
document.querySelector('body').appendChild(element);
How i can create these in ES6 like:
export default class Container extends HTMLDivElement {
constructor() {
super();
this.innerHTML = 'Content';
}
}
With these example?
var container = new Container();
document.querySelector('body').appendChild(container);
My idea is, to create an -only JavaScript- UI Framework, without using "native" HTML snippets...
<div class='body'>
</div>
<script>
class Container extends HTMLElement {
constructor() {
super();
console.log( 'Constructed' )
}
connectedCallback() {
console.log('Callback');
this.innerHTML = "Content";
}
}
customElements.define('my-contain', Container);
let container = new Container();
document.querySelector('.body').appendChild(container);
</script>
You need to register your Component with the CustomElementRegistry below your Class definition and utilize the connectedCallback().
export default class Container extends HTMLDivElement {
constructor() {
super();
this.innerHTML = 'Content'; // Does Nothing
}
connectedCallback() { // Fires when attached
console.log('Callback');
this.innerHTML = "Content";
}
}
customElements.define('my-contain', Container, { extends: "div" });
LIFECYCLE HOOKS OF CUSTOM COMPONENTS
More info on CustomElementRegistry here: MDN CustomElementRegistry
More info on implementation of such here: MDN Using Custom Elements
I made a simple example using Web Components with two custom elements (v1) where one is nested in another.
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="import" href="app-container.html">
</head>
<body>
<app-container></app-container>
</body>
</html>
app-container.html:
<link rel="import" href="toolbar.html">
<template id="app-container">
<app-toolbar></app-toolbar>
</template>
<script>
customElements.define('app-container', class extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({ mode: 'open' });
const content = document.currentScript.ownerDocument.querySelector('#app-container').content;
shadowRoot.appendChild(content.cloneNode(true));
}
});
</script>
toolbar.html:
<template id="app-toolbar">
<p>Ok!</p>
</template>
<script>
customElements.define('app-toolbar', class extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({ mode: 'open' });
const content = document.currentScript.ownerDocument.querySelector('#app-toolbar').content;
shadowRoot.appendChild(content.cloneNode(true));
}
});
</script>
But in the toolbar.html document.currentScript is the same as in the app-container.html and hence querySelector('#app-toolbar') can't find template with id app-toolbar. How to solve this problem?
Example tested on Chrome 55 (without polyfill).
document.currentScript contains a reference to the script that is currently parsed and executed. Therefore it is not valid anymore for your purpose when the constructor() function is called (from another script).
Instead you shoud save its value in a variable at the beginning of the script, and use this variable in the constructor:
<script>
var currentScript = document.currentScript
customElements.define( ... )
...
</script>
If you have multiple scripts, you should use distinct names.
Alternately, you can encapsulate the ephemeral value in a closure:
(function(owner) {
customElements.define('app-container', class extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({ mode: 'open' });
const content = owner.querySelector('#app-container').content;
shadowRoot.appendChild(content.cloneNode(true));
}
});
})(document.currentScript.ownerDocument);
Here the value document.currentScript.ownerDocument is assigned to the owner argument which is still defined correctly when constructor() is called.
owner is locally defined so you can use the same name in the other document.