I would like to write a jquery function that accepts either a dom element or its id as input:
function myfunction(myinput){
// pseudocode:
// if (myinput is dom element){
// var myID = $(myinput).attr('id');
// } else {
// var myID = myinput;
// }
// Do stuff with myID ...
}
Question: How can I tell whether myinput is a dom element???
To check if an element does not exist in the DOM: Use the getElementById or querySelector methods to select the element. Check if the stored value is equal to null . If the value is equal to null , the element does not exist in the DOM.
An Element object represents all HTML elements. Approach: In order to check whether a JavaScript object is a DOM object, we need to check whether the given JS object is of Element type Object. In order to check this, we will use instanceof operator.
We can use the tagName property and type attribute of the DOM element to check if the DOM element is input or not. For the input DOM element, the tagName is INPUT .
Answer: Use the jQuery val() Method You can use the val() method to test or check if inputs are empty in jQuery.
It's easier to do the check the other way around - check if it's a string if so use it to get an ID else treat it as a DOM node/element and handle it as if it was one.
function myfunction(myinput) {
var myId;
if (typeof myinput == 'string'){
myId = myinput;
} else {
myId = myinput.id; // myinput.id is enough
}
// do something
}
or if you really want to check against if it's HTMLElement then every DOM html element extends HTMLElement abstract interface. Check MDC for more info on HTMLElement.
...
if (myinput instanceof HTMLElement){
myId = myinput.id; // myinput.id is enough
} else {
myId = myinput;
}
...
In the end it won't really matter... your call!
Tom
You would implement your function like this:
function myfunction(myinput){
if (myinput.nodeType){
var myID = $(myinput).attr('id');
} else {
var myID = myinput;
}
// Do stuff with myID ...
}
More information about nodeType.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With