Jquery object compare problem - javascript

How to compare two Jquery object?
$('<p></p>')[0] === $('<p></p>')[0]
false
$('<p></p>') == $('<p></p>')
false
$('<p></p>').get() == $('<p></p>').get()
false

The following returns true
$('<p></p>').html() == $('<p></p>').html();
Is that what you need?
Edit: The old jQuery group^ discussion on this suggests comparing the child nodes in plain JavaScript since each jQuery object is an array of references to DOM objects. This function was also the accepted answer on this SO question.
^Tried the new jQuery forum but it has not imported the discussion correctly.

$('<p>') // it creates a new dom element.
//Equivalent to document.createElement('p')
so the two
$('<p></p>')[0] and $('<p></p>')[0]
are in fact two distinct DOM elements.

$('<p></p>')[0].outerHTML === $('<p></p>')[0].outerHTML; // true
$('<p>hi</p>')[0].outerHTML === $('<p></p>')[0].outerHTML; // false

I found a stupid solution ... anyone got better one?
$.md5($('<p></p>').get()[0].toString()) ==$.md5($('<p></p>').get()[0].toString())

Related

How to Check the variable value is [""] in JavaScript

Example:
When I check a variable containing this value [""] it returns false.
var th=[]
th.push("");
if($("#multiselect").val()==th)
It returns always false.
Thank you.
Edit 1:
changed Var to var. It was a typo.
Edit 2:
Actually, the problem I faced was I was trying to get the value from a multi-select input. The multi-select input sometimes returns values as [""] even I haven't selected any values basically it's a plugin. So I was confused and I thought [""] is a fixed primitive value like 1, 10, "bla blah",.. So I tried to compare it with the same array as the right-hand side of the '=' operator.
It was stupid. Now I posted the solution to my problem and I explained my stupidity.
there are two things:
Change Var to var
You can use includes method of Array as:
var th = [] <==== chnage Var to var
th.push("");
if(th.includes($("#multiselect").val())) { <=== you can use includes method of array
// DO whatever you want
}
Make sure var is lowercased.
You are accessing th as an array, so you’ll need to specify the index of the value you are checking: th[0]
Use triple equals, too: .val()===th[0]
Double check the jquery docs if you’re still running into trouble.
Happy coding!
A couple of things to consider:
You have a typo in the code above; var is valid; Var is invalid.
Browser will aptly complain to solve this typo.
You are comparing an array to DOM value; this will always be false.
DOM is a costly process. Unless the value associated is dynamic, its better to read once, store value into a variable and continue processing instead of reading from DOM always.
You could choose to try something on these lines:
let arr = [1,2,3,4];
let domValue = $("#multiselect").val();
arr.push(5);
arr.map((el, ix) => {
if el === domValue return true; //or choose to do something else here.
});
var th=[]; //It is var not Var
th.push("");
if($("#multiselect").val()==th[0]) // change th to th[0]
I am unable to comment so having to use an answer for now. Are you trying to check if an array has any values? If so you can use
if(th.length){
// do something
}
If you want to check a normal variable for empty string you can simply use
if(th == “”){
//do something
}
I found the solution after a couple of days when I posted this question. Now I can feel how stupid this question was.
Anyway, I'm answering this question so it might help others.
Answer to my question:
When two non-primitive datatype objects(which is the Array here) are compared using an assignment operator, it compares its reference of the object. So the object creation of both arrays would be different. If I want to check the array has [""] value, I should do something like the below.
function isArrValEmptyCheck(value) {
return !value || !(value instanceof Array) || value.length == 0 || value.length == 1 && value[0] == '';
}
console.log(isArrValEmptyCheck([""]));//returns true
console.log(isArrValEmptyCheck(["value1"]));//returns false
Sorry for the late response. Thanks to everyone who tried to help me.

Rewrite javascript functions for IE

I have some functions that either kill the page or fail silently in IE. I can't figure out how to rewrite them. I'd prefer not to have to add a bunch of plugins but I do have jQuery.
The variables in question are arrays of objects. How would you write the following?
// 1. Get only the newly added user / group
var new_students = new_enrollee_list.filter(function( new_enrollee ){
return ! current_enrollee_list.some(function( current_enrollee ){
return new_enrollee.id === current_enrollee.id && new_enrollee.type === current_enrollee.type;
});
});
// 2. Remove students from current list
current_enrollee_list.splice(0, current_enrollee_list.length, ...new_enrollee_list);
For the spread syntax you should be able to workaround by making one array from all the arguments and using Function.apply:
So this
current_enrollee_list.splice(0, current_enrollee_list.length, ...new_enrollee_list);
becomes
current_enrollee_list.splice.apply(current_enrollee_list, [0, current_enrollee_list.length].concat(new_enrollee_list));
Since you are using IE9 some and filter should work fine.

jQuery has conditional

Trying to write a conditional with jQuery that basically states, if div.gathering does not contain a.cat-link then do the following. I have tried the following but it doesn't seem to work. Can anyone shed some light on this?
if($("div.gathering:contains('a.cat-link')")){
$(".gathering").append("<a href='#"+data[i]["categories"][0]["category_id"]+"div' class='cat-link' id='"+data[i]["categories"][0]["category_id"]+"' rel='external'>"+data[i]["categories"][0]["category_name"]+"<br />");
}
How about this :
if($("div.gathering").find("a.cat-link").length == 0){
// Conditional statement returned TRUE
}
jQuery selectors return arrays of objects that matched the given selector. This is why we use the length property.
The method that you used - $("div.gathering:contains('a.cat-link')")
would return an empty array and when testing against any object that actually exists (even if it is an empty array) JavaScript will return true.
Example -
var nateArr = [];
if (nateArr){
// Do the dishes...
}else{
// Eat some waffles...
}
If you test this for yourself you will never stop washing those dishes because even though the nateArr contains zero elements it still exists therefore the conditional statement will always return true.
And your fingers will go all wrinkly
try this....
$("div.gathering:not(:contains(a.cat-link))")
.append("<a href='#"+data[i]["categories"][0]["category_id"]+"div' class='cat-link' id='"+data[i]["categories"][0]["category_id"]+"' rel='external'>"+data[i]["categories"][0]["category_name"]+"<br />")
this will only return the div with class gathering which does not have a.cat-link....
hope this helps....

Check if element exists [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Is there an “exists” function for jQuery
jQuery determining if element exists on page
if(tr) is returning true when tr is not an element, how do I check whether it's an element that exists?
var tr = $('#parts-table .no-data').parent();
$('.delete', row).bind('click', function (e) {
that.delete(e.currentTarget);
});
console.log(tr);
if (tr) //returns true when it shouldn't
Check its length property:
if(tr.length) {
// exists
}
if(tr) always evaluates to true because a jQuery object, or any JavaScript Object for that matter, is always truthy.
I always add this little jQuery snippet at the beginning of my JS files
jQuery.fn.exists = function(){return jQuery(this).length>0;}
This uses the same approach many here have suggested, but it also allows you to access whether or not an object exists like this:
if ( $('#toolbar').exists() ){
$('#toolbar').load(..., function(){...});
//etc...
}
That's because tr is a jQuery object, which is truthy (even when the jQuery object is empty). Use if (tr.length) instead, which will be true when length is not zero, false when it is zero. Or alternately, if (tr[0]).
How about:
if (tr.size() == 0)
try this
var tr = $('#parts-table .no-data').parent().length;

Test if two elements are the same

I would suspect this to work at first:
if ($('#element') == $('#element')) alert('hello');
But it does not. How does one test if elements are the same?
As of jquery 1.6 you can now simply do:
$element1.is($element2)
This should work:
if ($(this)[0] === $(this)[0]) alert('hello');
so should this
if (openActivity[0] == $(this)[0]) alert('hello');
Or just
if (openActivity[0] == this) alert('hello');
(without a new jQuery instance ;-)
As somebody already told, the same HTML element wrapped in two different moments generates two different jQuery instances, so they can never be equal.
Instead, the HTML elements wrapped may be compared that way, since the memory location they occupy is the same if it is the same HTML element, so:
var LIs = $('#myUL LI');
var $match = $('#myUL').find('LI:first');
alert(LIs.eq(0) === $match); // false
alert(LIs.get(0) === $match.get(0)) // TRUE! yeah :)
Best regards!
I would use addClass() for marking the opened and you can check that easily.
9 years later, without jQuery
If two elements are the same one, two elements must have the same pointer.
Thus,
document.body === document.body // true
document.querySelector('div') === document.querySelector('div') // true
document.createElement('div') === document.createElement('div') // false
Like silky or Santi said, a unique ID or class would be the easiest way to test. The reason your if statements don't work like you'd expect is because it's comparing 2 objects and seeing if they're the same object in memory.
Since it's always a new object getting created by $(this), they can never equal each other. That's why you have to test on a property of the object. You could get away with no unique id/class if each openActivity element was guaranteed to have different content that you could test against.

Categories

Resources