What separates an unregistered HTML Custom Element from a registered one?

If I forget to register a custom element, I can still:

  • customize the unregistered element using CSS
  • attach events to the unregistered element using JS

For example:

// REGISTER <my-custom-element-1>
class MyRegisteredCustomElement1 extends HTMLElement {
  constructor() {
    super();
  }
};

customElements.define('my-custom-element-1', MyRegisteredCustomElement1);

// ATTACH EVENT LISTENERS TO BOTH CUSTOM ELEMENTS
const myCustomElement1 = document.getElementsByTagName('my-custom-element-1')[0];
const myCustomElement2 = document.getElementsByTagName('my-custom-element-2')[0];

const customElementAlert = (e) => {

  switch (e.target.nodeName.toLowerCase()) {
  
    case ('my-custom-element-1') : console.log('I\'m a registered custom element and I can be scripted and styled.'); break;
    case ('my-custom-element-2') : console.log('I\'m an unregistered custom element. Nevertheless, I can be scripted and styled TOO.'); break;
  }
}

myCustomElement1.addEventListener('click', customElementAlert, false);
myCustomElement2.addEventListener('click', customElementAlert, false);
:not(:defined) {
  border: 1px dashed rgb(0, 0, 0);
}

my-custom-element-1,
my-custom-element-2 {
  float: left;
  display: inline-block;
  width: 100px;
  height: 100px;
  margin-right: 12px;
  padding: 6px;
  text-align: center;
  font-weight: bold;
  cursor: pointer;
}

my-custom-element-1 {
  color: rgb(255, 255, 255);
  background-color: rgb(255, 0, 0);
}

my-custom-element-1::after {
  content: 'I\'m a registered custom element.\A CLICK ME';
}

my-custom-element-2 {
  background-color: rgb(255, 255, 0);
}

my-custom-element-2::after {
  content: 'I\'m an unregistered custom element.\A CLICK ME';
}
<my-custom-element-1></my-custom-element-1>
<my-custom-element-2></my-custom-element-2>

Despite being able to style and script unregistered elements, what specific advantages does registering a custom element provide?

Answer №1

Essentially, it links the element to the designated class. This allows for:

  • utilizing lifecycle callbacks such as connectedCallback (and disconnectedCallback)
  • implementing custom logic and properties in the constructor.

The HTML element my-custom-element-2 that you have generated functions like a regular element unless assigned the specific class you provided. Upon inspecting the DOM, you will observe that the class of my-custom-element-2 is HTMLElement, while the class of my-custom-element-1 is myRegisteredCustomElement1.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using AJAX/jQuery to populate a SelectList in an MVC view

I have a C# MVC application where I am dynamically populating a dropdown based on a selected date using AJAX/jQuery. The action called retrieves a list of items for the chosen date. The issue I'm facing is that I've previously rendered a partial ...

Is there a way to efficiently parse HTML data returned as JSON in the browser using Cordova/Ionic?

Currently, I am retrieving data from a Drupal service and using AngularJS along with the ionic framework to create a hybrid app for mobile platforms, leveraging Cordova or Phonegap. You can check out my code on codepen: http://codepen.io/BruceWhealtonSWE/p ...

After successfully creating an account, the displayName consistently appears as null

I have a Vue project that utilizes Firebase as the backend. User registration is done using email and password. Below is the method used in Firebase: firebase.auth() .createUserWithEmailAndPassword(this.user.email, this.user.password) . ...

The size of my image decreases only when I transfer it to the phone screen

I have an image displayed on my website that I want to shift to the right specifically for mobile devices. @media screen and (max-width: 450px) { .my-img { padding-left: 8em; } } Although the image does shift to the right, it ends up shrinking in ...

Set the value of this input element to its current value decreased by

I currently have several tabs with input fields on each tab. I have assigned the same class to each input field so that I can transfer values from one tab to another using the following code: $('.group_input1').change(function(){ $('.g ...

Tips for handling an incorrect date entry when a field loses focus in AngularJS

If I have an <input> field with the type='date' attribute in its untouched state, it displays mm/dd/yyyy as the date format. I am looking to see if there is a way to utilize AngularJS ng-blur directive to reset the field to this original fo ...

Clearing the ng-model value in a controller following an ng-change event

Is there a way to reset the ng-model value in the controller after an ngChange event without needing to use a directive? <div ng-repeat="i in items"> <!-- Some DOM comes here --> <select ng-model="i.avail" ng-change="changeAvail(i. ...

Creating a handshake process for hybi-17

I am currently in the process of creating the handshake for the websocket hybi-17 protocol. I have been referencing the draft available at . Based on the guidelines provided in the draft, I have developed the following code snippets for both the client (us ...

I'm encountering CORS issues while attempting to log in using guacamole from my React app. Can anyone advise on what might be causing this problem

Having trouble logging into the Guacamole form through a React JS web application. The Guacamole server is hosted on Tomcat server, while the React app is on Node.js; both operating on separate domains. Despite using Nginx proxy on the server, encounteri ...

Showing the output of an HTTP request in hapi.js version 17.2.0

I am attempting to showcase a page utilizing the latest version of HapiJS 17, which has a dependency on HTTP requests. Essentially, I am consuming a REST API and then returning it using the new response toolkit known as 'h toolkit,' but an error ...

The interactivity of data-ng-click in HTML is not functioning as expected

I need help with implementing the data-ng-click functionality for a dynamically created button. Can someone assist me with this? var table = document.getElementById("dashboard"); for( var i = 0; i < $scope.namesOfMembers.length; i++ ){ var row = t ...

Tips for customizing styles when an element is being dragged over in Material-UI?

If I want to alter the backgroundColor when hovering, I can utilize sx={{"&:hover":{backgroundColor:"yellow"}} Is there a way to adjust the backgroundColor on dragover? It appears that sx={{"&:dragOver":{backgroundCol ...

What's the best way to apply a margin top to an image using Tailwind CSS?

Is there a way to adjust the top margin of an image in Tailwind CSS? I'm having trouble making my logo clearly visible and think giving it some space at the top might help. How can I do this within the Tailwind CSS framework? https://i.sstatic.net/Ae ...

Issues with JavaScript and CSS functionality not functioning correctly as expected

There seems to be an issue with the order of HTML elements in the following code. When I place the div with the class thumb-bar before the full-img div, the JavaScript functions correctly. However, if I switch their positions, the JavaScript functionalitie ...

Guide to creating a search bar that scans the text inside an external .txt file

Kindly scroll down to view the updated content, or read through from here for a better understanding of my requirements. I am seeking assistance from an expert in developing a website (not exactly my forte :D) which allows users to search for their banned ...

Transferring MySQL data into a spreadsheet format

I am currently attempting to export a MySQL database to an Excel sheet using PHP/MySQL. However, I keep encountering the following error message and despite trying everything, I have been unable to find a solution: Warning: mysqli_num_rows() expects par ...

What is the best way to apply different styles to alternative children within a dynamically generated list?

I am currently implementing the following code snippet: $('.js-toprow:nth-child(even)').css("background:", "#ddd"); $('.js-toprow:nth-child(odd)').css("background:", "#ff0000"); Within the function: function resetSlides() { conta ...

What could be the reason for the second selection not being chosen in a multi-select list?

When trying to select or deselect options in a multi-select using JavaScript, the code appears to be correct but encounters an issue when attempting to perform the same action multiple times. For example, if you try selecting Full-Time, click it again to ...

Identifying memory leaks caused by rxjs in Angular applications

Is there a specific tool or technique available to identify observables and subscriptions that have been left behind or are still active? I recently encountered a significant memory leak caused by components not being unsubscribed properly. I came across ...

AngularJS and the Angular UI Router were combined for the first time in

Hey everyone, I could really use some help as I'm just diving into the world of AngularJS. Can anyone guide me on how to tackle these pesky errors? Error: app.js:6 > Uncaught ReferenceError: angular is not defined Error: angular.min.js:6 > Unc ...