What is the JSDoc type for document.getElementById ('myID') and jQuery element?

I am trying to document my functions using JSDoc syntax.

/** * * My Description * * @param {JQuery|???} input * @returns {JQuery} */ function foo(input){ return $('selector'); } 

The above function accepts a single argument, which can be either a jQuery object or the element returned by document.getElementById .

What is a valid JSDoc type for getElementById return value?

For example, the following values ​​are valid:

 foo($('#input')); foo(document.getElementById('input')); 

Also, where can I find out in the future?

+7
javascript jsdoc
source share
5 answers

getElementById will always return a subtype of an Item . In the case of an HTML document, HTMLElement would be more appropriate

 document.getElementById('some-anchor').constructor //HTMLAnchorElement document.getElementById('some-div').constructor //HTMLDivElement 

In all cases, document.getElementById('some-element') instanceof HTMLElement will, IMHO, return true

+13
source share

While technically the return value of getElementById is equal to object , the documentation should help the developer know what it is.

I would personally go with Element , but there is no indication as to what you should use.

+4
source share

In your scenario, Element is what seems most appropriate, but usually you want to be as accurate as your code.

For example, using the latest extended IDEs, using Element will not autocomplete attributes such as disabled or readOnly . I find it useful to use, for example, HTMLInputElement @type.

+3
source share

HTMLElement or any can be used in your example.

 /** * @param {JQuery|HTMLElement} input * @returns {JQuery} */ function foo(input){ return $('selector'); } 
+1
source share

getElementById() will also return a javascript object.

in jQuery -> $ ('# input') simply wraps the element with the input id into the jQuery object so that jQuery methods can be applied to it.

So, in both cases, a type is an object.

 var x = document.getElementById('input'); alert(typeof x);// object 
0
source share

All Articles