bigskysoftware / bigskysoftware/htmx

HX-Retarget with a selector that has no elements results in a null error

Open
#2,216 5 comments 2 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
49.4k
Forks
1.7k
Avg merge
3d 22h
Merged PRs (30d)
30

Description

# Overview

When utilizing the `HX-Retarget` header with a selector that returns no elements, a null error when trying to access that non-existent target's `classList` occurs.

```
htmx.org@1.9.10:1 TypeError: Cannot read properties of null (reading 'classList')
at Mr (htmx.org@1.9.10:1:43638)
at b.onload (htmx.org@1.9.10:1:40710)
```

I believe this is because the header-based retargeting logic does not validate or do anything if the resultant target is null. Other areas of the code such as `issueAjaxRequest` when using the DOM-based `hx-target` attribute *do* perform this check and raise an error event if it cannot be found:

```
htmx.org@1.9.10:1 htmx:targetError
```

I think it's worth doing similar when retargeting.

# Example

```go
package main

import "net/http"

func main() {
s := http.NewServeMux()

s.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`





Do something



`))
})

s.HandleFunc("/component", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("HX-Retarget", "closest .anything-goes-here")
})

http.ListenAndServe("localhost:9389", s)
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.