5

I want to create a custom HTML element that behaves exactly like the built-in <div> element. I'm trying to prevent a <div> soup. I would for example want to have a <currency-list> element. This element should behave exactly like the <div> element. The only difference is the name. How can I achieve this?

Thanks, Yosemite

7
  • 2
    are you aware there are other tags beside <div>? Commented Oct 24, 2021 at 15:47
  • What is the question here? We know (vaguely) what you want; whats stopping you? Commented Oct 24, 2021 at 15:47
  • There are other tags apart from div. Like <main></main> or <article></article> and yes they do help organize your code and also help with SEO. Have a look here w3schools.com/html/html5_semantic_elements.asp Commented Oct 24, 2021 at 15:49
  • 1
    MDN:Using_custom_elements Commented Oct 24, 2021 at 15:57
  • 2
    HTML kind of has enough semantic elements, so unless you can explain what problem you're really trying to solve (because "div soup" is principally caused by creating completely unnecessary tags, not by the fact that they're divs) this feels like an XY problem, where you're asking for help in addressing a symptom, rather than the problem itself. Commented Oct 24, 2021 at 15:59

1 Answer 1

2

a DIV (HTMLDivElement) is a block element.

But you don't even need a defined Custom Element/Web Component to make a block element

customElements.define("currency-list", class extends HTMLElement {
  connectedCallback() {
    this.style.display = "block";
  }
});
another-list {
  display: block;
}

body>*:defined {
  background: green;
  color: beige;
}

body>*:not(:defined) {
  background: lightgreen;
}
Line 1
<currency-list>Hello Web Component</currency-list>
Line 3
<div>Line 4</div>
Line 5
<another-list onclick="alert(this.constructor.name)">Line 6</another-list>
Line 7

Notes:

  • <another-list> is an HTMLUnknownElement; nothing wrong with using it, its constructor is an HTMLElement, so can do everything an HTMLElement can do.
    For more on the value of Unknown Elements see my Dev.to post

  • You can set any CSS display value on a DIV, you can't on your own Elements, as it will destroy the display:block setting.

PS. tag your SO questions web-component and/or custom-element

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.