Check if element exists [duplicate] - javascript

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;

Related

What does an if (number) return?

I seem to be having a hard time understanding what this does to my code?
const $counters = $('.js-item-counter')
if($counters.length)
{
}
What would this if statement return?
I can tell that the value is 1, but does this make sense?
I am trying to fix some frontend issues, and ran into something like this..
In Javascript, 0 is a falsey value. Anything other than 0 is considered true.
So what your code is doing is, it is making sure that the $counters is present in the DOM because if it were, it would give the length of > 0.
.length property tells you how many elements of the given selector are present in the DOM. If it is 0, then the element isn't present. If it is more than 0, then the element is present and you can act upon it as you wish.
The if statement will return true or false based on the condition.
If $counters.length > 0, it will return true and if block will be executed. Otherwise, it will return false and block won't be executed.
It returns true if the number inside the if statement is greater than or equal to 1 and false if it is 0.
It's a simple test to see if any elements of that class exist. Using length of a jQuery object is the most common jQuery approach to count matches in the collection
If it is anything other than zero it is truthy and zero is falsy
There used to be a size() method but that was deprecated and if you read in it's docs it tells you to use length instead
if the target element is stand for integer that having initial value of 1, then you should do this way
if($counters > 1)
{
//note length is only for checking of element existance
}
length coerced to true for any length other than 0 and false for 0:
console.log(
!!0,
!!1,
!!10
);

Javascript Shorthand to Check if val Equals One of Two [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 5 years ago.
I feel like I come across this a lot and that intuitively, there should be a way to do something like this:
if (userType ==="admin" || userType === "superUser"){
// do stuff
}
In a more elegant way, like this:
if (userType === ("admin" || "superUser")){
// do stuff
}
Obviously that^ doesn't work because if the first value resolves to true, it will never check if it's the second ("superuser").
Is there shorthand to do this in a JS if-statement where you wouldn't have to repeat the variable name?
Switch statements don't count! ;D
JavaScript doesn't provide out of the box such a syntax.
Now, you can do something of close enough with the Array.includes() method.
It returns true if the element is found in the array.
Otherwise if returns false.
var userTypes = ["admin", "superUser"];
if (userTypes.includes(userType)){
// do stuff
}
or by inlining the array value :
if (["admin", "superUser"].includes(userType)){
// do stuff
}
you can use an array with indexOf. something like
if(["superUser", "admin"].indexOf(userType) >= 0){
//code goes here
}
You could use an object for fast checking.
if ({ admin: 1, superUser: 1 }[userType]) {
// do something if true
}

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

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

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