Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 customElements - adding pseudo-classes

I'm working on a custom HTML class, which can be used as an additional type of form that supports any element matching the [name] and [value] attributes.

However, when extending a class, I found out that I couldn't get the pseudo-select :invalid working.

class HTMLInlineInputElement extends HTMLElement{
    constructor(){
        super();
        this.addEventListener('input', function(event){
            this.value = this.innerHTML;
        })
    }
    connectedCallback(){}

    get name(){
        return this.getAttribute('name');
    }
    set name(value){
        return this.setAttribute('name', value);
    }
    get value(){
        return this.getAttribute('value');
    }
    set value(value){
        return this.setAttribute('value', value);
    }
    get valid(){
        return this.validity.valid;
    }
    set valid(value){
        return this.validity.valid = value;
    }
    checkValidity(){
        if( this.hasAttribute('required') &&  this.value == null || this.value.length == 0 ){
            console.log('req');
            this.valid = false;
        } else if( this.hasAttribute('pattern') && this.value.match( this.getAttribute('pattern') ) ){
            console.log('patt');
            this.valid = false;
        }
    }
}

if( typeof customElements !== 'undefined' ){
    customElements.define('inline-form', HTMLInlineFormElement);
    customElements.define('inline-input', HTMLInlineInputElement);
} else {
    document.createElement('inline-form', HTMLInlineFormElement);
    document.createElement('inline-input', HTMLInlineInputElement);
}

In a nutshell: I want to add the HTMLElement.invalid = true; functionality to my class so I can use the :invalid selector in CSS. What can I do to add :is-selectors to my new class?

like image 758
BRO_THOM Avatar asked Nov 05 '25 05:11

BRO_THOM


1 Answers

From everything I have read you can not use the :invalid selector in CSS for custom elements. But you can set the invalid attribute based on validity and then use the [invalid] selector instead.

Try changing your code to the following:

get valid(){
  return !this.hasAttribute('invalid');
}
set valid(value){
  if (value) {
    this.removeAttribute('invalid');
  }
  else {
    this.setAttribute('invalid'), '');
  }
}
like image 119
Intervalia Avatar answered Nov 06 '25 19:11

Intervalia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!