Declarative-ish JavaScript API for creating DOM?


#1

I noticed that ParentNode.append() returns undefined, but if it returned this, then it would be possible to write stuff like this:

          document.body.append(
            document.createElement('div').append(
              document.createElement('span').append(
                'hello'
              ),
              new MyElement().append(
                new MyOtherElement().append(
                  document.createElement( 'div' ).append(
                    document.createElement('select').append(
                      document.createElement('option').append('option1'),
                      document.createElement('option').append('option2'),
                      document.createElement('option').append('option3')
                    )
                  )
                )
              )
            )
          )

which is somewhat “declarative”. Does any native API exist like that? It would also be easy to map JSX to that.

I know we can create these APIs ourselves. Just wondering about native options.


#2

Updated the title, because obviously HTML is a declarative API. I meant to ask about declarative JS API.


#3

Does any native API exist like that?

nope, but people have been talking about that:


#4

document.createElement could accept the arguments to append directly (as array).


#5

Actually, why not just use JavaScript (html) Tagged Template Literals?


#6

Because it seems like string-parsing overhead at runtime. Or not?


#7

HTML and JavaScript parsing is already costly enough. Just look at the original post -^ It’s much more costly than the equivalent HTML.

Also, instantiating this in one go is more efficient. And Template Literals can easily be pre-compiled and re-used. The equivalent JavaScript code has to be re-executed. (Any one of the various symbols could have changed)


#8

Apple proposed extending the <template> element to handle interpolation, which might be similar enough to what you’re looking for?

w3c/webcomponents: HTML Template Instantiation


#9

@Androbin @Tigt Interesting replies, thanks!

I checked out Surplus recently, it looks really nice too: converts JSX to in-place updates, similar to hyperHTML or lit-html approaches, but faster without DOM diffing.


#10

This might be close to what you are looking for:

Inspired by kotlin-like layout parameters.

Lit-html also comes to mind, with string literals.