Hacker News new | past | comments | ask | show | jobs | submit login

What is the benefit of mixing js and html?

    el = <button>Click me</button> as HTMLButtonElement;
What would be the downside of

    el = html.button('<button>Click me</button>');
?

That way no compilation step would be needed and debugging would be easier as the code executed in the browser is the same code the developer writes.




The benefit is that it makes people puke from looking at it so you have more job security I guess. Putting xml onto the same line with a scripting language is like mixing toothpaste and orange juice.

I don't understand why people take such offense to calling document.createElement() or document.getElementById() or kind of document. or window. function. It's consistent and native.


Compare

    class Item extends EventTarget {

        #checkbox = <input type='checkbox' /> as HTMLInputElement;
        li;

        constructor(private list: List, text: string) {
            super();
            this.li = (
              <li class='item'>
                {this.#checkbox}
                <span onclick={() => this.toggle()}>{text}</span>
                <button class='close' onclick={() => this.remove()}></button>
              </li> as HTMLLIElement
            );
            this.#checkbox.onclick = () => this.toggle();
        }
    }
    
with

    class Item extends EventTarget {

        #checkbox;
        li;
        
        constructor(private list: List, text: string) {
            this.#checkbox = createElement('input');
            this.#checkbox.setAttribute('type', 'checkbox');
            
            this.li = document.createElement('li');
            this.li.className = 'item';
            this.li.appendChild(this.#checkbox);

            const span = document.createElement('span');
            span.onclick = (() => this.toggle());
            span.textContent = text;
            this.li.appendChild(span);

            const button = document.createElement('button');
            button.className = 'close';
            button.onclick = (() => this.remove());
            this.li.appendChild(button);
        }
    }
    
Of course you can create helper functions to avoid all the `createElement`s followed by `setAttribute`s. As mentioned elsewhere you can even used tagged strings. But doing things "manually" is painful.


With the first example you have syntax highlighting and compile-time check.

With the second of you have stringa.


If you use a html`` tagged template literal combined with the html-in-template-string vs code extension you get syntax highlighting. A simple html identity literal function is a one-liner: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...


Why wouldn't one be able to tell syntax highlighters and code checkers that the string that goes into the html.something() functions is html?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: