0

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
Nicero
  • 4,181
  • 6
  • 30
  • 52

1 Answers1

1

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>

1cg
  • 1,392
  • 3
  • 8
  • 1
    Hi 1cg! Why I can't do (or why hyperscript does'nt offer) something like this: _="on click call setID() then add .green to it" where I simply use the result ('it') of the call? Woud'nt be more natural and easier? – Nicero Apr 01 '21 at 14:36
  • First solution <#${getIdToAddTo()}/> worked fine. Second solution reported A target expression must be writable : functionCall undefined – Nicero Apr 01 '21 at 14:59
  • The `setID()` returns a string? In this case you still need to use a query literal to get at it, to provide as an argument for the add command. – 1cg Apr 05 '21 at 17:02
  • Ok, now I understand (I'm using ver. 0.0.9) – Nicero Apr 07 '21 at 08:08