Test if two elements are the same - javascript

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.

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.

Not repeating selectors in a conditional statement with JavaScript/jQuery

I have a small app with one form and one input field. When a user submits this form, I first want to see if the value only contains letters. If all is good, I want to pass the value on to a function.
Here's what I have:
$('form').on('submit', function(e) {
if ($('input').val().match(/^[a-zA-Z]+$/)) {
someFunction($('input').val());
} else {
// Error message or something else here
}
e.preventDefault();
});
I don't like writing $('input').val() twice (once in the conditional statement, and again if it holds true). Using this wouldn't work, since it's within a conditional statement and not some sort of function... Is there a way to not repeat code in this scenario?
Perhaps setting $('input').val() to a variable would be best?
Thanks!
Just do this:
var inputValue = $('input').val();
Bit old but I found this helpful : Not repeating selectors
var myvar = $('input');
As well as the clear discription :
basically every time you use $(someselector) you iterate through the dom. If you can you should store the element reference

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....

Trying to get some jQuery functions to run in order. Is callback the issue?

I'm trying to do some things in order, and I'm having some trouble.
When the button with the id #sub_button is clicked,
Make sure each element with class ".verify" has it's own object value (see code)...
... if not, blur that element (will run some other code and create an object for it).
AFTER the above IF check is COMPLETE (now all elements should have an object), THEN run function "isitgood". (The "isitgood" function is running before all elements get their object values, which is done on blur)
$("#sub_button").click(function() {
$(".verify").each(function(){
objtitle = $(this).attr('id');
if (!myObj[objtitle]) {
$("#"+objtitle).blur(); // Define anything undefined
}
}); // end each
isitgood();
}); // end click function
function isitgood(){
if (myObj.login_id == "ok" && myObj.email == "ok") {
// submit the form
} else {
// shows error
}
}
Also, once I get this executing in the right order, it would be nice to do some sort of .each loop to check if all the object values == "ok" instead of specifying all of them in the function. All of the names of the objects (ie. login_id, email) are the ID attr of any element with class name .verify.
Well, you could do a quick index check in the click callback:
var sub_buttons = $("#sub_button");
sub_buttons.click(function() {
$(".verify").each(function(index){
objtitle = $(this).attr('id');
if (!myObj[objtitle]) {
$("#"+objtitle).blur(); // Define anything undefined
}
if (index == sub_buttons.length - 1)
isitgood();
}
}); // end each
}); // end click function
This will check if you're on the last element in the jQuery object, and if so, will run the isitgood() function. This way, you make sure that you're finished with the $.each method before executing isitgood()
Javascript is asynchronous. Your isitgood() will always fire while .each is still doing it's thing.
That said from your code it's not clear what you're trying to accomplish. The way you're using .each seems to indicate that you have multiple of the same ID attributes on your tags. That won't work, IDs have to be unique. Also you seem to be mixing jQuery and regular Javascript. Use one or the other. Actually just use jQuery, you'll save yourself time and effort!
If you do have unique ids then you shouldn't need the .each at all. Just check the appropriate ids with your if statement.
Please provide more of your code and i can update this with a better answer. For instance what does your myObj look like? How do elements of it get the value of ok? It doesn't seem to get set within your call to .each().

Jquery object compare problem

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())

Categories

Resources