4

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?

2 Answers 2

1

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'), '');
  }
}

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

Comments

1

There is currently a proposed addition to the web components spec that would allow for the addition of custom pseudo-elements. You can track the discussion (any maybe help move it forward) on GitHub.

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.