Question

I'm trying to document my functions with 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 an element returned by document.getElementById.

What is the valid JSDoc type for the return value of getElementById?

For example, the following are both valid:

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

Also, where can I find this out in future?

Was it helpful?

Solution

getElementById will always return a subtype of Element. In the case of an HTML document, HTMLElement will 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

OTHER TIPS

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

I'd personally go with Element but there is no indications as to what you should use.

In your scenario Element is what seems to be the most suitable, but generally speaking you want to be as accurante as your code permits.

For instance, using recent advanced IDEs, using Element won't provide autocompletion for attributes such as disabled or readOnly. I find it useful to use, for instance, the HTMLInputElement @type instead.

HTMLElement or any can be used in your example.

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

getElementById() will also return a javascript object.

in jQuery -> $('#input') just wraps the element with an id of input into a jQuery object so that jQuery methods can be applied on it.

So in both cases the type is an object.

var x = document.getElementById('input');

alert(typeof x);// object
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top