Extract the textContent of an element using hyperscript

44 views Asked by At

I have 2 elements in the DOM

<div 
   id="info_globals" style="display: none;" 
   hx-trigger="htmx_post_validation_trigger from:body" 
   hx-target="#info_globals" 
   hx-get="<snip>" 
   hx-include="[name='original_trigger_fld']" 
   hx-swap="innerHTML" 
   class=""
>
    <script id="info-length-lower" type="application/json">6</script>
    <script id="info-length-upper" type="application/json">6</script>
</div>

And I need to get these in some hyperscript on one of the form fields, but nothing seems to give me a value. I've tried several variations:

The post validation trigger is issued by some inline validation on the form triggered via htmx. This works OK. The update of these values also works OK.

The url for this calls an endpoint that is a django TemplateView, and the get method is overridden as follows.

    def get(self, request: HttpRequest, *args: str, **kwargs: Any) -> HttpResponse:
        response = super().get(request, *args, **kwargs)
        response["HX-Trigger"] = "htmx_post_globals_updated"
        return response

This is what I've thought would work, but neither seems to be.

set lowerBound to the textContent of #info-length-lower
set lowerBound to #info-length-lower.textContent

... and a few others along the way that I've forgotten now.

If I log this info out

log "globals updated"
set lowerBound to #info-length-lower.textContent
set upperBound to #info-length-upper.textContent
log "lower:", lowerBound, "upper:", upperBound

The console output is

globals updated
lower: "" upper: ""

How can I get this information out using hyperscript?

1

There are 1 answers

0
michjnich On

OK, so yes, @mariodev, set lowerBound to #info-length-lower.textContent should work, and in fact does.

The issue was to do with the fact that the trigger was running before the new values had been swapped into the HTML.

Changing the HX-Trigger to HX-Trigger-After-Swap solved this problem and allowed things to run in the correct sequence.

The reason it looked like it was the set not picking up values, is because initial values are empty (there's nothing to base them on yet, because the deciding field is also empty) so the process was going:

  1. Trigger runs the hs set statements on existing empty values
  2. hx-swap goes through
  3. Values are now correct (when you look!) but too late!

Changing the trigger meant that the flow became:

  1. hx-swap goes through
  2. Values are now correct
  3. Trigger runs the hs set statements