Skip to content

Uncaught TypeError: link is null #1132

@gleb-kun

Description

@gleb-kun

What happened?

I found the following situation. In Firefox I noticed the following errors in the console:

Uncaught TypeError: link is null
    buildIdToNavigationElementMap http://localhost:1313/ts/main.js:345
    buildIdToNavigationElementMap http://localhost:1313/ts/main.js:343
    setupScrollspy http://localhost:1313/ts/main.js:381
    init http://localhost:1313/ts/main.js:444
    <anonymous> http://localhost:1313/ts/main.js:491
[main.js:345:20](http://localhost:1313/ts/main.js)
    buildIdToNavigationElementMap http://localhost:1313/ts/main.js:345
    forEach self-hosted:157
    buildIdToNavigationElementMap http://localhost:1313/ts/main.js:343
    setupScrollspy http://localhost:1313/ts/main.js:381
    init http://localhost:1313/ts/main.js:444
    <anonymous> http://localhost:1313/ts/main.js:491

This happens if you don't specifically specify sections in post markdown. For example, let's say there is such a configuration hugo.yaml:

params:
  widgets:
    page:
      - type: toc

markup:
  tableOfContents:
    endLevel: 4
    ordered: true
    startLevel: 2

And the following markup with sections in something post markdown:

## Section 1

Something text

## Section 2

Something text

##

There should have been a "Section 3" heading in this section, but it was accidentally omitted.

## Another section

Something text

Essentially this is fixed by adding a check in the buildIdToNavigationElementMap function:

function buildIdToNavigationElementMap(navigation: NodeListOf<Element>): IdToElementMap {
    const sectionLinkRef: IdToElementMap = {};
    navigation.forEach((navigationElement: HTMLElement) => {
        const link = navigationElement.querySelector("a");
        if (link) {
            const href = link.getAttribute("href");
            if (href.startsWith("#")) {
                sectionLinkRef[href.slice(1)] = navigationElement;
            }
        }
    });

    return sectionLinkRef;
}

Hugo version

0.145.0+extended+withdeploy linux/amd64

Theme version

newest

What browsers are you seeing the problem on?

No response

More information about the browser

No response

Relevant log output

Link to Minimal Reproducible Example

The example is described above.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions