$("#myElement").length vs. !!$("myElement") to check if the dom element exists? - javascript

I need to check if a certain dom element exists or not. I saw other posts which suggests length property to check that. That works fine. But It works even without length property. For example:
!!$("#myElement"); // true
!!$("#myElement").length; // true
Both the ways return same value. So is it ok to not use length property to check if the element exists?

No, always use length.
Your logic here is flawed as a jQuery object is never empty or null, it always returns an object even if no element is selected, hence you cannot reliably coerce it to a boolean to see if the selector matched any elements.
console.log(!!$('#exists')); // should be true
console.log(!!$('#doesNotExist')); // should be false
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="exists"></div>
As you can see above, both tests return true.

Related

Javascript Bug: set audio object controls attribute True = = False

I'm rather new to this and don't know exactly how to report a bug, but I first want to confirm it's a bug and then go on from there. But here's what I'm finding:
1) When creating an audio object controls attribute, the controls attribute will respond to a string as if it's a boolean.
For Instance:
<button onclick="example()">Try this</button>
<script>
function example() {
var aud = document.createElement("AUDIO");
aud.setAttribute("src","example.mp3");
aud.setAttribute("controls", "controls");
}
Okay, we've put controls in there because it makes controls equal controls:
Thing is, you can put any old string in there and it works just fine -- apple, banana, pear, anything.
2) Isn't the value suppose to be a boolean? Well when you try a boolean, false for example, you still get true. (False == True) It works just as if you typed in true.
...and if you put anything else other than true or false (just type anything other than an integer, string, or true or false value), you get false (or it just doesn't work).
Everything equals true and a non-string, non-integer equals false (or just doesn't work).
Finally, you can even try setting the controls attribute on an accessed audio element:
var aud = document.getElementById("idhere");
function accessAudioElement() {
aud.controls = false;
}
At least here the true and false actually work as true and false, but once again, any string or integer will also get you true and any non-string/non-integer will break the code.
Can somebody help me out here because I don't think this is suppose to work this way... and if does, what's the point of using a boolean value when most anything else will work?
Of course I'm still learning, so maybe this is not a bug, maybe for some reason this is suppose to work this way, but if that's the case would someone please share the logic behind this with me.
I'm just not understanding.
Thanks Magic
This is an extended answer of what #nnnnnn suggested in the comments.
aud.controls = false; doesn't set the attribute, it sets the property.
You need to use setAttribute() method to add the specified attribute to an element.
aud.setAttribute("controls", "controls");
And use removeAttribute() method removes the specified attribute from an element.
aud.removeAttribute("controls");
For more reading on these methods, have a look at the hyperlinks attached.
Element.setAttribute()
Element.removeAttribute()
When to use setAttribute vs .attribute= in JavaScript?
HTML - attributes vs properties
You might want to read/search more about Javascript Truthy $ Falsey. It is very important.
https://j11y.io/javascript/truthy-falsey/

How do I find out whether an element with that ID exists or not?

I do a:
console.log($('#test'));
I know that test doesn't exist. If I do a console.log, it doesn't output undefined/null. Rather it ouputs something like an empty array and when I check that array it looks like it returns the jQuery object itself.
I also tried:
if ($('#test')){
//do something
}
But it still doesn't work. I want to know whether the ID I am selecting exists on page or not. How do I do that using jQuery?
It's something like 20x faster to do this:
if (document.getElementById("test"))
compared to the jQuery operation to just determine if a DOM object with that id exists in the page. jQuery can do a lot for you, but when its general selector engine and general object structure isn't needed, it's not the quickest way to do things.
As others have said, $("#test") is always a valid jQuery object, even if #testdoesn't exist. If the #test object doesn't exist, then $("#test") will be a jQuery object that has no DOM objects in it (the internal array will have a .length === 0), but it's still a valid object.
In JavaScript, objects are always truthy, so using it in that fashion will always pass the condition.
You need to check the length property. A response of 0 is falsy, and will work as expected.
if ($('#test').length) {
// ...
}
This is unlike document.getElementById(), which returns null if the element with that id attribute does not exist.
If this is confusing, you could always write a quick jQuery plugin.
$.fn.exists = function() {
return !!this.length;
};
You can then call exists() on a jQuery collection, to ensure that selector has matched at least one item.
Use '(' and ')' for 'if' statements, and check if the returned array has length greater than 0:
if ($('#test').length > 0){
//do something
}
use something like this
if ($('#test').length > 0){
alert('hi')
}else
{
alert('hello')
}
Live Demo ​
Use
if ($('#test').length > 0){
//do something
}
the length tells you how many items were selected if it is 0 no element has the id test.
best way for this is to check length of the selected element
if ($('#test').length > 0){
//do something
}
But if you want to create a exist function jQuery welcomes you just add the line in your script
jQuery.fn.exists = function(){return this.length>0;}
and now you can Check if element exist or not
if ($(selector).exists()) {
// Do something
}
console.log($('#test'));
This won't print the value because it represents the object found in the DOM with the id test.
If you want to get values, use $("#test").val(); or $("#test").html();
If you want to check existence, do the length test as suggested above.
Also, if you're testing for the existence of a generated element (something you added to the DOM), make sure you checkout .live (http://api.jquery.com/live/). This is need for all elements that are created after the page is loaded.

What does the jQuery function $('#myelement').is('*') do?

What does the following code do:
$('#myelement').is('*')
What does the asterisk signify? Since there is only one element, #myelement, I can't understand the point of using is(), which checks if an element matches a set of elements?
This is some seriously existential JavaScript.
$('#myelement').is('*')
It will fail whenever #myelement doesn't exist, and return true otherwise.
Basically check to see if an element exists or not. Not the best method...
is checks the element fits the criteria. In this case, "*" means all elements.
So, it simply returns true if the previous selector returns anything.
Take a look here for an example: http://jsfiddle.net/b7DwB/
http://api.jquery.com/is/
Pretty much what it does well from my understanding of it at least, and how I tend to use it. Is return true or false on whatever its called on.
Example I have a checkbox that I want to make sure is checked before I submit my form via AJAX I would do something like
if( $('input#tosCheck').is(':checked') ){
/*its checked submit form*/
}else{
alert('Error');
}
All in all the link to the API from jQuery better describes it then I ever could, but I wanted to at least share an example of use to help you gauge some idea.
Can't say I've ever seen that jQuery code used before, but it seems to be a poor way of checking for the existence of an element. Since * is the universal selector, the expression in question will always return true if #myelement exists, otherwise it will return false.
I say this is a "poor" way of checking the existence of an element because you can simply check the length of the jQuery object instead:
$('#myelement').length > 0
I haven't done any testing, but I assume the above is faster since it doesn't have the overhead of the is() function call.

Jquery if div doesn't exist

I'm using 1 js for 2 different pages. 1 page doesn't have a div which the other does. So when I submit the values, I get a $( js error
for
$('.description'+save_id+'').html(description_val).show(); //update category description
I suspect that I get the error because there is nothing to show(). Is there a short code I can use to detect if the div.description exists otherwise don't do the function?
jQuery will not error if it has nothing to perform on. The show() would not be a problem. To answer your question, though, you can check the length property on the jQuery object returned from $.
If the description_val variable is undefined, then the code will fail.
Try using an if() statement to only run the code if description_val is not undefined.
if(description_val) {
$('.description'+save_id+'').html(description_val).show();
}
Or if for some reason the value of description_val may be a value that would equate to false, then do this:
if(description_val !== undefined) {
$('.description'+save_id+'').html(description_val).show();
}
From what you posted I'd check to make sure the variables you're using are all defined at this stage. To check for existence you can do this:
if ($('.description' + save_id).size() > 0) {
// code here that operates on the div.
}
This is essentially just a syntactic alternative to checking the length property.

select by id in jquery

as all you know
$("#ID")
returns the element having ID.
but this code always return even there's no element.
alert($("#htrBuyerCouponNotice"));
alert(document.getElementById("htrBuyerConponNotice"));
in this case.
those two line results are diffrent.
I want to check whether there is an element has htrBuyerCouponNotice.
document.getElementByID return null if there's no element.
You can check the length property of the jQuery object to determine the number of matched elements, e.g.:
alert($(selector).length);
You can use it directly on if statements e.g.:
var $el = $(selector);
if ($el.length) { // only 0 will coerce to false
// ...
}
But most of the time you don't really need to know if the selector matched elements or not, because the jQuery built-in methods will be simply ignored, e.g.:
$('#nonExistent').hide();
The above statement will not cause any error even if the element was not found.
jQuery has also the size method, but I would recommend you to use the length property directly since it's publicly accessible, the size method is slightly slower since it is only a function that returns the value of length property.
because jQuery returns a list of selected elements, if there are no elements, you still get a return - its just a empty list.
check for $('#someID').length - should work if i remember corretly
When selecting elements, jQuery will always return an array of matching elements. In your case, $('#htrBuyerCouponNotice') is probably returning an empty array. Instead, check $('#htrBuyerCouponNotice').length.
Andrew
Try:
$("#htrBuyerCouponNotice").size()
It'll be zero if there's no nodes with that identifier, 1 if there is.

Categories

Resources