Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Uncaught TypeError: node.getAttribute is not a function when passed an empty node list #230

Closed
haacked opened this issue Oct 6, 2020 · 0 comments

Comments

@haacked
Copy link

haacked commented Oct 6, 2020

Thanks for this great library! I found a potential bug with it though.

Suppose I have the following script that loads on every page.

document.addEventListener("DOMContentLoaded", () => {
    timeago.render(document.querySelectorAll('time.timeago[datetime]'));
});

It works great when a page has elements that match that query selector. But for a page that doesn't match the query selector, I get the following exception.

Uncaught TypeError: node.getAttribute is not a function
Uncaught TypeError: node.getAttribute is not a function
    at getDateAttribute (dom.ts?670d:9)
    at eval (realtime.ts?6dbd:63)
    at Array.forEach ()
    at Module.render (realtime.ts?6dbd:62)

The bug seems to be this line:

const nodeList: HTMLElement[] = nodes.length ? nodes : [nodes];

This assumes that if there's no length property, then it's a node and not a node list. However, if a node list is empty, the nodes.length returns 0 which is interpreted as false, which then falls back to the [nodes] clause, thus creating an array consisting of one empty node list.

I think the correct behavior would be to change this to:

const nodeList: HTMLElement[] = NodeList.prototype.isPrototypeOf(nodes) ? nodes : [nodes];
gabalis added a commit to gabalis/timeago.js that referenced this issue Mar 12, 2021
Implementation of the fix suggested in issue hustcc#230

'Uncaught TypeError: node.getAttribute is not a function when passed an empty node list'
hustcc pushed a commit that referenced this issue Jan 8, 2024
Implementation of the fix suggested in issue #230

'Uncaught TypeError: node.getAttribute is not a function when passed an empty node list'
@hustcc hustcc closed this as completed Jan 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants