If, Or & Else custom elements

April 17, 2026 ยท View on GitHub

Show/hide stuff based on input element values.

TODO

  • Multiple values could be done as attributes like <if- value-1="" value-2="" value-3=""> etc and then observed via MutationObserver instead of static observedAttributes. Would be and by default and you could slap an or in there to have any of the values match like <if- value-1="" or value-2="">. And since html only considers the last one of multiple same named attributes, that lends itself to a nice syntax in the attributes where you can slap the or between all the values if you like.

Docs

Works inside forms, but you can also put these outside forms and use the form attribute, just like you would on input elements.

Uses FormData to evaluate the conditions, so works with any type of input elements (including hidden inputs) and should work for any custom elements that participate in forms.

Uses the hidden attribute, so does not need any styling out of the box, but feel free to style any way you like.

Grab ifelse.js into your project. Define your elements. Name them whatever you like. I like them short.

import { If, Or, Else } from './ifelse.js'
customElements.define("if-", If)
customElements.define("or-", Or)
customElements.define("else-", Else)
<form>
  <label for="animal">What's your favourite animal?</label>
  <input id="animal" name="animal">
  <p>
    <if- name="animal" value="Giraffe">Giraffes are the best!</if->
  </p>
</form>
  • Reacts to user input & change events. Send a change event manually from an input element if you need to re-evaluate the ifs of the form in response to something other than user input.
  • Toggles hidden based on given condition. Set initial visibility before elements have been initialized or evaluated (or in case there's no js) by using the hidden attribute yourself.
  • name attribute checks if FormData includes an entry with that name.
  • value attribute checks if FormData includes that value
  • name + value check if FormData includes that value for that name.

If you need more complex conditions, run your condition expression in javascript and set the expression result as a value on a hidden input. Check more complete example usage in index.html & index.js. (https://sakamies.github.io/conditional-elements/)


Licence, NPM module?

This repo does not have a licence and is not on NPM. Feel free to learn from this, fork the code or make a package. Give credit and behave.

I don't expect the API of this element to ever change, but I'm not sure I want to be a package maintainer.