Check if something works - javascript

I'm trying to test what is available on a specific browser (JavaScript-wise).
If I just typed this for example:
function checksetAttribute(){
if(document.getElementById("blar").setAttribute("name","blarDiv")){
alert("Your browser supports it.");
}
else{
alert("Your browser does not support it.");
}
}
Would this return a true answer as to whether or not the property(ies) work?

If you want to test whether a certain property works, not whether setAttribute works, then this is the wrong approach, as setAttribute always returns undefined (== false). Instead, test whether the element has the attribute name as a key - and use a new element instead of one pulled from the DOM, because elements in the DOM could have been modified.
function attributeWorks(attr, within) {
return document.createElement(within || 'div').hasOwnProperty(attr);
}
I added the within parameter because some properties exist only on certain types of elements: for example, if you always test against a <div>, then the function will return false for href.
If you want to test whether the setAttribute function works this is still the wrong approach, because, if setAttribute is not implemented, trying to execute it will throw an error instead of returning false. We can use the same method as above, with the simplification that we already know the parameters:
function setAttributeWorks() {
return document.createElement('div').hasOwnProperty('setAttribute');
}

No. Assuming the browser supports document.getElementById and setAttribute, it will just set the name attribute. As that method returns void (which is falsy), it will always alert "Your browser does not support it." - unless an Exception is thrown.
It neither will check whether the browser supports name attributes.

I am guessing that the code you have there would fail if "setAttribute" was not supported.
var a = document.createElement("div");
if(a.setAttribute){
alert("VERY SUPPORTED");
}else{
alert("Not supported");
}
This would check to see if the setAttribute method is available on dom elements.

Related

What does $.support.placeholder mean in jQuery?

I don't understand this condition: $.support.placeholder
Can anyone explain to me what this is for?
if ($.support.placeholder) {
alert("Testing");
} else {
return;
}
It's checking to see if the placeholder property on the $.support object is truthy¹ and, if so, it does the alert; if not, it does a return, exiting the function this code is in.
jQuery's support object (long deprecated, it shouldn't be used anymore) tells you what the current browser supports. From the link:
A collection of properties that represent the presence of different browser features or bugs. Intended for jQuery's internal use; specific properties may be removed when they are no longer needed internally to improve page startup performance. For your own project's feature-detection needs, we strongly recommend the use of an external library such as Modernizr instead of dependency on properties in jQuery.support.
(my emphasis)
In this case, the check is seeing if the browser supports the placeholder attribute on input elements. But see above, the check is unreliable. If jQuery no longer needs to know this information internally, the property may be removed, and that code would be tricked into thinking the browser didn't support placeholder (which nearly all do) because getting the value of a property that doesn't exist results in undefined, which is falsy.
In fact, the current version of jQuery as of this writing (v3.3.1) doesn't have placeholder:
console.log("typeof $.support.placeholder:", typeof $.support.placeholder); // "typeof $.support.placeholder: undefined"
var input = document.createElement("input");
input.type = "text";
var supportsPlaceholder = "placeholder" in input;
console.log("supportsPlaceholder: ", supportsPlaceholder); // "supportsPlaceholder: true" (in nearly all browsers)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The code in the question would incorrectly report that your browser doesn't have placeholder support even when it does.
¹ a truthy value is a value that coerces to true when used as a boolean, such as in an if. A falsy value is one that coerces to false. The falsy values are null, undefined, 0, NaN, "", and of course, false; all other values are truthy.

When document.getElementByID is used without an ID what is it doing?

I have some code I am looking at that is using a variation on getElementByID that I do not understand. I have looked online but I am not finding anything that explains this.
I understand how to use something like document.getElementByID("bob"), however what I am looking at says:
if (document.getElementByID){}
When you use getElementByID in this fashion what is it doing?
document.getElementById returns the function which can be used to get some element by ID.
typeof document.getElementById; // 'function'
However, if some browser didn't implement getElementById, you would get undefined.
Therefore, this is just a test to ensure that the method exists before calling it, avoiding an error.
if(document.getElementById) {
// Hopefully it's safe to call it
document.getElementById("bob");
// ...
} else {
alert('What kind of stupid browser are you using? Install a proper one');
}
This will return false:
if (document.getElementByID){}
because there is no getElementByID on the document object. There is however, getElementById (notice the difference in the d at the end).
Therefore, this will return true
if (document.getElementById){}
In short, if getElementByID exists on document, which because of the typing, does not, but if it did then do something.
A more full example using the right spelling:
if (document.getElementById) {
// it is safe to use this method because it exists on document
var element = document.getElementById('foo');
}
document.getElementById returns a function which evaluates to true when in an expression. You can test this out yourself but running the code snippet.
console.log(document.getElementById);
// The !! forces a boolean
console.log(!!document.getElementById);

how to check if an object exists in javascript

I want to check if the window.sessionStorage object exists. Is this the way to do it:
if (window.sessionStorage)
in javascript?
if(sessionStorage.length == 0) {
//do something
}
That will validate whether sessionStorage is empty or not. Alternatively, you can use this:
if(typeof(sessionStorage) == 'undefined') {
//do something
}
Use can use modernizr to check session/web storage and other browser features.
In case you can't add the lib, check how they handle it here
Cheers.
Your proposed solution will work since we know that the sessionStorage property must refer to an object—and objects always resolve truthy in expressions.
However a word of caution, when checking for the existence of any arbitrary property in JavaScript (where we don't necessarily know the value), it's safest to check that the key exists in the object of interest. For example:
var exists = (someObject && 'someProp' in someObject);
We need to do this because someProp could be a valid property yet the test would fail when equal to: false, "", 0, or any other value that would be falsey in an expression.

What does this javascript code means?

I'm working on a form that does changes on the fly and I'm trying to understand it better.
nonetheless, I came upon and input that has this and I was wondering what does this statement means any example would be appreciated. Thank you
onclick="if(this.onchange){this.onchange();}"
This is checking to see if this has a function defined as onchange. In javascript, you don't need if (this.onchange != null). If the value is null, undefined, or has an empty string, the value in the if statement returned is false. This is usually a good practice to avoid null reference errors in javascript when you aren't positive that every browser is going to support whatever you're attempting to use. (or other reasons I'm missing now)
For example, when adding a line to output to the console in Google Chrome...
console.log("output here");
This may cause errors in other browsers if I remember correctly. A good way to handle this would be to use:
if (console) { console.log("output here"); }
In simple terms,
"If this element has function associated to it's onchange event listener, execute it.".
It's a way to check if it is declared
if (typeof this.onchange != "undefined"){
this.onchange();
}

Tree view using javascript and css

I am doing a tree view like by referring this link
I am getting this error in firebug
**Non-standard document.all property was used.
Use W3C standard document.getElementById() instead.
return document.all[id].style[property];**
How to use document.getElementById() at that place
This error message means that you accessed the property "all" of the variable document, but this property is, let's say, deprecated, so should not be used. The console says that you should use a method "getElementById", which returns the element with given id, on which you can then proceed.
To access the element by id if you know the id, you can for example, declare a variable and assign to it the result of getElementById (there is going to be a problem with style[property]):
var myElement=document.getElementById("id");
return myElement.property; // height for example
or just
return document.getElementById("id").property; // height for example

Categories

Resources