简体   繁体   中英

how can I tell if an element is a jquery DOM element or vanilla?

How can I tell if a DOM element $('.hello') is either a jquery element or vanilla javascript? I have code that takes in a jquery element and performs operations to it, but I would like the code to also take in vanilla javascript elements and do the same thing. How would you go about doing this? Basically, the code works regardless of whether the element is jquery or vanilla.

You can check it by (obj instanceof jQuery) === true

For example -

function doSomething(element) {

  $elm = (element instanceof jQuery !== true) ? $(element) : element;
  // do something with $elm and jQuery

}

You can also re-wrap the element with $() even if it's already a jQuery object as it's allowed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM