How to know if the passed object is a DOM element?

3

I'm working with functions in which I must pass ( Mandatory ) a DOM element. This function will work with the properties of this DOM element.

Example

function changeValue(elem, value){
  elem.value = value;
}

var input = document.getElementsByTagName('input')[0];
changeValue(input, input.value.toUpperCase());
<input name="name" value="Guilherme" />

Doubt

  • How to check if the element is really a DOM element? and not an instance of jQuery or { value : 'Guilherme'} .
asked by anonymous 21.11.2016 / 19:09

1 answer

4

You can use the function below, removed from this answer.

function isElement(o) {
  return (
    typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
    o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string"
  );
}

console.log(isElement(document.getElementById("campo"))); // elemento
console.log(isElement($("#campo"))); // objeto jQuery
console.log(isElement($("#campo")[0])); // elemento
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="campo">
    
21.11.2016 / 19:18