DEV Community

Discussion on: Post an Elegant Code Snippet You Love.

 
efpage profile image
Eckehard

Sure, in that case it's just a question of convenience. But you can also build nested elements, so it´s a way to compose your page or parts of it :

        let d, h, b, count = 0
        d = div([
            h = h1(`${count}`, { style: { color: "red" } }),
            b = button("CLICK")
        ])
        b.onclick = () => h.innerText = ++count
        document.body.append(d)
Enter fullscreen mode Exit fullscreen mode

By the way, CSS styles use a syntax, which is a bit different from JSON:

<p style="color:blue;font-size:46px;">
Enter fullscreen mode Exit fullscreen mode

With your approach, people need to translate the style definition like this:

 createElement("p",{style: {color:"blue";font-size:"46px;"})
Enter fullscreen mode Exit fullscreen mode

As you need to process the styles anyway, would it not be better to use the usual syntax?

 createElement("p",{style: "color:blue;font-size:46px;")
Enter fullscreen mode Exit fullscreen mode

If you do not want to process the CSS manually, you can use this function:

function setStyle(el, css){
  el.setAttribute('style', el.getAttribute('style') + ';' + css);
}
Enter fullscreen mode Exit fullscreen mode