How to use variables in _hyperscript js

853 Views Asked by At

I'm having fun with _hyperscript js which I find very promising and amusing.

Now I'm trying to understand the use of variables inside simple commands. Suppose that I have the following code generated by a PHP script that queried a dB and where ids are obtained the dB (a very common case):

<div id="1000">Mercedes</div>
<div id="1022">Audi</div>
<div id="1301">Ferrari</div>
<div id="1106">Lamborghini</div>

To add a class to a specific id I would normally do like this:

<button _="on click add .green to #1022" type="button">
    Click
</button>

But what if I don't know the id because it's the result of a dB query? How can I place a variable using _hyperscript and set it with javascript? Something like this:

<button _="on click call setID() then add .green to ???" type="button">
    Click
</button>

<script type="text/javascript">
    function setID() {
        // here the code to get the ID 
        return id;
    }
</script>

Using the 'symbol' it to read the result of the last call returns error:

_="on click call setID() then add .green to it"

returns

Uncaught TypeError: target.classList is undefined
1

There are 1 best solutions below

4
On

You can use string templates inside query literals, so something like this should work:

<button _="on click add .green to <#${getIdToAddTo()}/>" type="button">
    Click
</button>

where the <.../> is the query literal and the ${getIdToAddTo()} is a string template within that query

Another alternative would be to create a method that returns the div to add to:

<script>
  function divToAddTo() {
    return document.getElementById("whatever");
  }
</script>
<button _="on click add .green to divToAddTo()" type="button">
    Click
</button>