Chapter 2. Your first Web Component

 

This chapter covers

  • The basis for almost every element you use: HTMLElement
  • Extending classes to make your own custom elements
  • Giving your custom elements logic and interactivity
  • Using custom elements after defining them with customElements.define

As I promised in the beginning of this book, we’re going to start small. Luckily, with Web Components, even when we do start small, we can still make something meaningful. After this chapter, you’ll have the know-how to make your first Web Component and be able to view it right in your browser! Subsequent chapters through this book will explore key concepts in more detail, but the basics start here. At the end of this chapter, we’ll discuss options when your browser doesn’t support custom elements, as in the case of the latest consumer Edge release (at the time of writing) or IE. For now, though, please use Chrome, Firefox, or Safari if you’d like to follow along with the code examples.

2.1. Intro to HTMLElement

Prior to learning the basics of Web Components, I didn’t really know what an HTMLElement was. You might not either—it’s an easy thing to never come across, because while it’s a core concept in how the DOM works, we’ve typically never worked with it directly until now.

This is because when you add an element to your page, it just works. You don’t necessarily need to know how an <input> tag is related to a <button> or how a <div> is related to an <img>.

2.2. Rules for naming your element

2.3. Defining your custom element (and handling collisions)

2.4. Extending HTMLElement to create custom component logic

2.5. Using your custom element in practice

2.6. Making a (useful) first component

2.7. Notes on browser support

Summary

sitemap