I have a bit of JS code, which creates a new, custom HTML element. I need to move the child elements to the new parent, which is inside the custom element (I need two elements because of styling), but as elements put inside the tags are created first, I need to have all children of moved to the last child of (I already create the new parent automatically). Note: jQuery solutions are acceptable.
Code:
connectedCallback() {
this.setAttribute('class', 'e1')
const e1 = document.createElement('div')
e1.setAttribute('class', 'e-content')
this.appendChild(e1)
}
class ce extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.setAttribute('class', 'e1')
const e1 = document.createElement('div')
e1.setAttribute('class', 'e-content')
this.appendChild(e1)
}
}
customElements.define('custom-elem', ce);
<custom-elem>
<p>A child of custom-elem, which should go in the generated child of custom-elem (div with class e-content).</p>
</custom-elem>
Looks like adding two statements (could likely be reduced to one) to the end of the connectedCallback function should cover it:
class ce extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.setAttribute('class', 'e1')
const e1 = document.createElement('div')
e1.setAttribute('class', 'e-content')
this.appendChild(e1)
var pElement = this.getElementsByTagName('p')
e1.appendChild(pElement[0])
}
}
customElements.define('custom-elem', ce);
<custom-elem>
<p>A child of custom-elem, which should go in the generated child of custom-elem (div with class e-content).</p>
</custom-elem>
Use the browser's inspector to see that the <p> element is moved to inside the <div class="e-content"> element.