I have a function that I want to be able to allow passing in either a regular javascript DOM element object or a jQuery object. If its not yet a jQuery object I will then make it one.
Does anyone know of a very reliable way to detect this.
function functionName(elm){
//Detect if elm is not a jquery object in condition
if (elm) elm = $(elm);
}
A logical approach is to detect one of the properties of the DOM element object. The question is, which property would be the most reliable to detect?
I could also just make it a jquery object either way since jQuery doesn't have a problem with something like: $($imajQueryObjAlready); However, the purpose of this question is not to just solve the problem, but to find a good way to detect if its a DOM object vs. a jQuery object.
To test for a DOM element, you can check its nodeType property:
if( elm.nodeType ) {
// Was a DOM node
}
or you could check the jQuery property:
if( elm.jquery ) {
// Was a jQuery object
}
To test for a jQuery object, you can use the instanceof operator:
if(elm instanceof jQuery) {
...
}
or:
if(elm instanceof $) {
...
}
jQuery does it like this:
if ( selector.nodeType )
(jQuery 1.4.3, line 109)
The easiest way is to simply pass it into the jQuery function either way. If it's already a jQuery object, it will return it unchanged:
function(elem){
elem = $(elem);
...
}
From the jQuery source code, this is what's happening:
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
Where makeArray is merging the new (default) jQuery object with the passed in one.
elm instanceof jQuery is the most foolproof way, as testing elm.nodeType would mistake {nodeType:1} for a DOM element, and testing elm.jquery would mistake {jquery:$()} for a jQuery object, in addition to there being no guarantee future jQuery objects won't have a jquery property.
The classy way:
function is_jquery_object(x) {
return window.jQuery && x instanceof jQuery;
}
function is_dom_object(x) {
return window.HTMLElement && x instanceof HTMLElement;
}
Building on #karim79's answer, if you need to be sure it's either a DOM or jQuery object, use these tests. (The window test helps the function fail gracefully if the class is not defined, e.g. jQuery failed to load.)
Related
I'm trying to figure out the vanilla equivalent of the following code:
$(document).attr('key', 'value');
So far I've looked into
document - it's not an element so you cannot call setAttribute on it
document.documentElement - returns the html tag. This is not the same "element" that jquery is targeting
$(document)[0] seems to return a shadow element in Chrome Inspector
$(document).attr('key', 'somethingUnique') doesn't exist in the Chrome Inspector
Is jQuery creating it's own shadow element mock of the document so it can treat it like a real element? What element is jQuery actually referencing when you do $(document)?
A jQuery results set is an array like object that in general holds DOMElement, but jQuery does not really care about what type the objects in the result set have. Neither the DOMElements nor any other element that is stored within the jQuery result set is somehow mocked/wrapped, they are directly stored in the result set. jQuery tries to figure out what it has to do to those objects by looking at their available functions.
When you call .attr, jQuery checks for each object in the set if it has the function getAttribute if this is the case it assumes that it also has a function setAttribute.
If it does not have a function getAttribute, then it will forward the function call to the .prop() function, and prop will internally just do:
elem[name] = value
So if you pass a plain object to jQuery, then it will just set its property.
var a = {
}
$(a).attr('test', 'hello world');
console.dir(a) // for `a` the property `test` is set
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you add a getAttribute and setAttribute function to that object then jQuery will call those:
var a = {
getAttribute() {
},
setAttribute() {
console.log('setAttribute was called')
}
}
$(a).attr('test', 'hello world');
console.dir(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
However, you should always assume, that the way and order how jQuery does these tests might change. Moreover, only rely on it if it is mentioned explicitly in the documentation.
I believe you're incorrect about $(document) not referring to document, thus, the answer is (quite simply):
document['key'] = 'value'
E.g. In Chrome:
> $(document)[0] === document
true
> $(document).attr('blarg', 'narf')
n.fn.init [document, context: document]
> document.blarg
"narf"
> document.foo = 'bar'
"bar"
> document.foo
"bar"
jQuery is just assigning the value to document directly.
$(document).attr('test', 'hello world');
console.log(document['test']); // prints "hello world"
I really thought jQuery would have wrapped DOM elements, since for some reason, I never write var x = $('#x') to reuse it later but recall $.
That´s why I wrote:
Yes it is wrapped
But after reading #t.niese answer here I tried
var x = $('#x')
var y = $('#y')
var ref = x[0]
x[0] = y[0] // hack jQuery Object reference to DOM element
setTimeout(() => x.html('1'), 1000) // actually writes in #y
setTimeout(() => x.html('2'), 2000) // actually writes in #y
setTimeout(() => { x.push(ref) }, 2500) // hack jQuery Object reference to DOM element
setTimeout(() => x.html('3'), 3000) // actually writes in both #x and #y
And understood I don't write var x = $('#x') not because it is a wrapped object, but exactly because it is not a wrapped object.
I thought the entry point of the API was $, but I may see the API like var api = $(), and the entry point as (el) => api.push(el) or (sel) => api.push(document.querySelector(sel))
I can $().push but I can not $().forEach nor shift nor unshift but yes delete an index, also
In the example
setTimeout(() => { x.map((item) => {console.log(item)}) }, 3500)
logs 0 and 1, not the elements. Tested using jQuery version 3.3.1
I need to determine if a jQuery object has the jQuery .click() event, if not I need to use the JavaScript one: $("#Call")[0].click()
Basically I need a way to this (this is pseudo code):
if ($("Call").click() == valid){
$("Call").click()
} else {
$("Call")[0].click()
}
Not sure why you would need to do it, but to answer your question would mean you need to look up where jQuery stores it's events. if there is an event for that type, there will be an array, if there is no event, than it is undefined.
var evtData = $._data($("#Call").get(0)).events;
var hasClickAttached = evtData && evtData.click !== undefined;
This question already has answers here:
jquery: test whether input variable is dom element
(4 answers)
Closed 9 years ago.
I was wondering how can i pass two different type of value in a single function which accepts single parameter.
let a function is function a(b){return c;}
i'm trying to pass a string while calling the function a some places like a('a string value') then i'll do something with it. Now i need to pass a html element like a(jquery('#someDiv')) and then i'll some another stuff. I need to differentiate both in the function declaration.
Any idea from the experts?
Thanks in advance.
EDIT:
I was looking for a tip to check the data type i'm going to pass as the parameter of the function a. It can be a string or a number or an object or even a function. I don't want to use a fallback. I want to use the last else statement to through an error or exception.
The typeof operator can be used to test for strings.
if (typeof b == 'string') {
//handle string
}
The second part is a bit more tricky. typeof will return object for a jQuery object. I believe it is safe enough to check if the object's [[Prototype]] is the same as the jQuery constructor's prototype using Object.getPrototypeOf:
else if (Object.getPrototypeOf(b) === $.fn) {
//it is an object that inherits from the jQuery prototype
}
But that isn't supported in IE<9. If a fallback is necessary, instanceof will have a similar effect and can be used instead of Object.getPrototypeOf:
else if (b instanceof jQuery) {}
So a complete solution with old IE support:
if (typeof b == 'string') {
//handle string
} else if (b instanceof jQuery) {
//handle jQuery object
} else {
throw 'Invalid argument';
}
* Note that instanceof will return true even when a constructor "subclasses" jQuery (has a link in the prototype chain to jQuery), while Object.getPrototypeOf will only return true if the object's internal [[Prototype]] points to the same object as the jQuery constructor's prototype. It is rather rare when this will make a difference, but worth keeping in mind.
Nevertheless of these small quirks, this related question has instanceof as the accepted answer, as it is the most compatible solution.
And to explain a couple things, jQuery itself is not a constructor, but its prototype object is shared with jQuery.fn.init which is the actual constructor, and jQuery.fn is a shorthand for jQuery.prototype, so:
jQuery.fn.init.prototype === jQuery.prototype
jQuery.prototype === jQuery.fn
This is going a little off-topic already, so here's a more in-depth article for the interested readers: How jQuery instantiates objects as jQuery.fn.init, and what that means if you want to subclass jQuery
I have a function that has the signature of:
function(id,target){
//do stuff
}
The target parameter is assumed to be a jQuery wrapped object however it is possible that it could be a dom element in which case I'd like to wrap it in jQuery before I do operations on it. How can I test the target variable for jQuery?
if(!(target instanceof jQuery)) {
target = jQuery(target);
}
You can use instanceof
obj instanceof jQuery
Check if object is a jQuery object
Because jQuery is a widely used and mature collaborative effort, I can't help but to look at its source for guidance in writing better Javascript. I use the jQuery library all the time along with my PHP applications, but when I look under the hood of this rather sophisticated library I realize just how much I still don't understand about Javascript. Lo, I have a few questions for the SO community. First of all, consider the following code...
$('#element').attr('alt', 'Ivan is SUPER hungry! lolz');
vs
$('#element').attr({'alt': 'Ivan is an ugly monster! omfgz'});
Now, is this to say that the attr() method was designed to accept EITHER an attribute name, an attribute name and a value, or a pair-value map? Can someone give me a short explanation of what a map actually is and the important ways that it differs from an array in Javascript?
Moving on, the whole library is wrapped in this business...
(function(window, undefined) { /* jQuery */ })(window);
I get that the wrapped parentheses cause a behavior similar to body onLoad="function();", but what is this practice called and is it any different than using the onLoad event handler? Also, I can't make heads or tails of the (window) bit there at the end. What exactly is happening with the window object here?
Am I wrong in the assessment that objects are no different than functions in Javascript? Please correct me if I'm wrong on this but $() is the all encompassing jQuery object, but it looks just like a method. Here's another quick question with a code example...
$('#element').attr('alt', 'Adopt a Phantom Cougar from Your Local ASPCA');
... Should look something like this on the inside (maybe I'm wrong about this)...
function $(var element = null) {
if (element != null) {
function attr(var attribute = null, var value = null) {
/* stuff that does things */
}
}
}
Is this the standing procedure for defining objects and their child methods and properties in Javascript? Comparing Javascript to PHP, do you use a period . the same way you would use -> to retrieve a method from an object?
I apologize for this being a bit lengthy, but answers to these questions will reveal a great deal to me about jQuery and Javascript in general. Thanks!
1. Method overloading
$('#element').attr('alt', 'Ivan is SUPER hungry! lolz');
vs
$('#element').attr({'alt': 'Ivan is an ugly monster! omfgz'});
var attr = function (key, value) {
// is first argument an object / map ?
if (typeof key === "object") {
// for each key value pair
for (var k in key) {
// recursively call it.
attr(k, key[k]);
}
} else {
// do magic with key and value
}
}
2. Closures
(function(window, undefined) { /* jQuery */ })(window);
Is not used as an onload handler. It's simply creating new scope inside a function.
This means that var foo is a local variable rather then a global one. It's also creating a real undefined variable to use since Parameters that are not specified passes in undefined
This gaurds againts window.undefined = true which is valid / allowed.
the (window) bit there at the end. What exactly is happening with the window object here?
It's micro optimising window access by making it local. Local variable access is about 0.01% faster then global variable access
Am I wrong in the assessment that objects are no different than functions in Javascript?
Yes and no. All functions are objects. $() just returns a new jQuery object because internally it calls return new jQuery.fn.init();
3. Your snippet
function $(var element = null) {
Javascript does not support default parameter values or optional parameters. Standard practice to emulate this is as follows
function f(o) {
o != null || (o = "default");
}
Comparing Javascript to PHP, do you use a period . the same way you would use -> to retrieve a method from an object?
You can access properties on an object using foo.property or foo["property"] a property can be any type including functions / methods.
4. Miscellanous Questions hidden in your question
Can someone give me a short explanation of what a map actually is and the important ways that it differs from an array in Javascript?
An array is created using var a = [] it simply contains a list of key value pairs where all the keys are positive numbers. It also has all the Array methods. Arrays are also objects.
A map is just an object. An object is simply a bag of key value pairs. You assign some data under a key on the object. This data can be of any type.
For attr, if you give an object instead of a key value pair it will loop on each property.
Look for attr: in jQuery's code, then you'll see it use access. Then look for access: and you will see there is a check on the type of key if it is an object, start a loop.
The wrapping in a function, is to prevent all the code inside to be accessed from outside, and cause unwanted problems. The only parameters that are passed are window that allow to set globals and access the DOM. The undefined I guess it is to make the check on this special value quicker.
I read sometimes jQuery but I didn't start with it, may be you should get some good books to make you an idea first of what some advanced features Javascript has, and then apply your knowledge to the specifics of jQuery.
1 - Yes attr can accept a attribute name for getting a value, a name and a value for setting one value or a map of attribute names and values for settings more than one attribute
2 - A map is basically a JavaScript object e.g:
var map = {
'key1' : 'value1',
'key2' : 'value2'
};
3 - (function(window, undefined) { /* jQuery */ })(window); is something called an anonymous function as it doesn't have a name. In this case it also executes straight away.
A simple example would be:
function test(){
...
}
test();
//As an anonymous function it would be:
(function(){
...
}();
//And it you wanted to pass variables:
function test(abc){
...
}
test(abc);
//As an anonymous function it would be:
(function(abc){
...
}(abc);
this would make it different to the load event, as it is a function not an event.
4 - window is passed as a variable, as it is used internally within jQuery
5 - Objects and functions the same, as everything in JavaScript is an object. jQuery does something like this:
var obj = {
"init" : function(){
}
}
6 - Yes you can use . to retrieve a value on an object but you can also use [] e.g:
var map = {
"test" : 1
}
map.test //1
map["test"] //1
I hope this answers your many questions, let me know if I've missed anything out.
jQuery 1.6.1
The test is typeof key === "object"
if that is true, then you passed a { .... }
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.attr );
},
// Mutifunctional method to get and set values to a collection
// The value/s can be optionally by executed if its a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},