Skip to content

Instantly share code, notes, and snippets.

@utsavsomaiya
Created August 28, 2024 16:23
Show Gist options
  • Save utsavsomaiya/47374286fe92e4f54b75228d53a0ff0d to your computer and use it in GitHub Desktop.
Save utsavsomaiya/47374286fe92e4f54b75228d53a0ff0d to your computer and use it in GitHub Desktop.
My custom web element
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<my-custom-element />
<script>
class MyCustomElement extends HTMLElement {
constructor() {
super()
const shadow = this.attachShadow({ mode: 'open' })
const wrapper = document.createElement('div')
wrapper.setAttribute('class', 'wrapper')
const style = document.createElement('style')
style.textContent = `
.wrapper {
background-color: #f0f0f0;
padding: 10px;
border: 1px solid #ddd;
font-size: 16px;
}
`
shadow.appendChild(style)
shadow.appendChild(wrapper)
wrapper.textContent = 'Hello, I am a custom element!'
}
connectedCallback() {
console.log('Custom element added to page.')
}
disconnectedCallback() {
console.log('Custom element removed from page.')
}
}
customElements.define('my-custom-element', MyCustomElement)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment