A good[ish] website

Web development blog, loads of UI and JavaScript topics

JavaScript: check if function parameter is a string or an object

Filed under: JavaScript— Tagged with: jquery

If a function takes a DOM element as a parameter, it can be a string, or a jQuery object, for example. Or why not both? With a small conditional check it's possible.

Take the following example, where the function simply gets element's dimensions and returns and object:

var getElementDimensions = function (el) {
  var $el = $(el)

  return {
    width: $el.width(),
    height: $el.height()

It expects the only parameter to be a string. But wouldn't it be nice if it could be a jQuery object also? Turns out it's pretty easy to do:

if (typeof myVar == 'string' || myVar instanceof String) {
  // Sting
} else {
  // Not a string. Since the function only takes
  // a string or an object, this level of checking
  // should be sufficient

This is exactly what ternary conditional statements are made for, the function in it's final form:

 * Gets element height and width as an array
 * @param  {mixed}  elem jQuery object or a string
 * @return {object}      Object with two nodes, width, and height
var getElementDimensions = function (el) {
  // Check if parameter is string or object
  var $el = typeof el == 'string' || el instanceof String ? $(el) : el

  return {
    width: $el.width(),
    height: $el.height()

Usage example:

// Give it a jQuery object
var $el = $('#some-element')
var dim = getElementDImensions($el)

// Or just a string
var dim = getElementDImensions('.some-element')

// Either way, `dim` now has width and height

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!