0

I want to make sure that a parameter that is passed to a function is an element and not a number or a string so my program does not crash?

function myFunction(element){ 
  console.log(element.style.color)
}
6
  • 2
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 27, 2020 at 22:19
  • 2
    You probably want to check more than it not being a number or a string. Commented Jul 27, 2020 at 22:20
  • in 2020 you can refer it as element?.style?.color . that is the simplest possible way and pretty safe of crashes Commented Jul 27, 2020 at 22:20
  • @Andrei good suggestion, but that doesn't make it safe. Commented Jul 27, 2020 at 22:20
  • You can get some interesting information from param.__proto__.toString() and "" + param.constructor and param.tagName — you can also check if several attributes exist that all Elements will have and (most) other things won't. Commented Jul 27, 2020 at 22:34

1 Answer 1

2

Perhaps you're looking for HTMLElement:

function myFunction(element) {
  if (element instanceof HTMLElement) {
    console.log(element.style.color)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.