Search code examples
javascripthtmlchromiumshadow-dom

How can I interact with browser-inserted Shadow DOM content in an input field?


Currently I am trying to set a function that will click on the little clock inside of <input type=time> but am unable to find the innerHTML of the tag to find the clock.

enter image description here

This is what I want to do:

html

<input id='timeInput' type='time'/>

JS

document.getElementById("timeInput").children('clockIcon').click()

But when I run a document.getElementById('timeInput').innerHTML I get null.

I believe that this has something to do with the Shadow DOM, but have been unable to find the information about the shadow DOM input.

I have previously been able to check the hidden browser HTML, but am unable to find that previous resource. Any ideas?

To specify, my app only shows on Chrome and Opera browsers since it is a Chrome extension.


Solution

  • There's no way to interact with the shadow DOM. The whole purpose of a shadow tree is to isolate functionality, behavior, and styles from the outside world - even if the mode is "open". If the author of a particular component wants you to be able to control the behavior or styles, they will provide an API for doing so. If the author does not provide an API for it, they don't want you mucking around with it.

    When it comes to using form fields, my rule of thumb is to always follow one of these rules:

    1. Use the browser form fields as they come - don't try to get too fancy with it as you will likely break accessibility, keyboard navigation, autofill and other things you didn't intend to break. Anything more than styling the borders, background, and padding is usually not a good idea. You might think it is, but I can likely prove you wrong by showing how you broke some default behavior.

    For example, automatically displaying a time picker would take focus away from what the user was doing. Maybe the screen reader was reading some text, or a power user was tabbing through the navigation using their keyboard, and then all the sudden they're on the time picker when they didn't want to be.

    1. Use a widely tested UI library. The authors of popular UI libraries have taken into account all of the behaviors and such so as to provide a smooth and predictable experience for users. Use these when you want to do things like automatically display a date/time picker or some other fancy behavior you probably shouldn't be doing but are going to anyways.

    Whatever you do, don't try to roll your own fancy form controls. I guarantee you will piss off one of your users.