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

Asked

Viewed 76 times

3

I’m working with functions I must pass on (Mandatorily) an element GIFT.
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'}.

1 answer

4


You can use the function below, I removed from this reply.

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>
<input type="text" id="campo">

  • Has an update. "The Previous code didn’t work in Chrome because Node and Htmlelement are functions Instead of the expected Object."

  • Well noted! I changed adding the current version. =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.