How to capture null in javascript - javascript

i try to detect null this way
if(!$(this))
{
alert('here is null');
}
OR
if($(this)===null)
{
alert('here is null');
}
but still no luck.
here is partial code
$elements.each(function(){
//alert($(this).html());
var $item = $('<li />').append($(this));
if(!$(this))
{
alert('here is null');
}
//alert($item.text());
$list.append($item);
});
anyone can see full code from here https://jsfiddle.net/tridip/41s1pq3a/12/
edit
i was iterate in td's content. td has some link and text. i was trying to wrap each text and link inside li. so iterate this below way. code is working but some time it is also showing null which i need to detect.
i am looking for way not consider any null or empty.
here is the code
var $elements = $('.webgrid-footer td').contents()
.filter(function() {
return this.nodeType === 3 || this.nodeType === 1; // 1 means elements, 3 means text node
});
var $list = $('<ul />');
$elements.each(function(){
//alert($(this).html());
var $item = $('<li />').append($(this));
if(this===null)
{
alert('here is null');
}
//alert($item.text());
$list.append($item);
});
//alert($list.html());
$('#dv').append($list);
see this line var $item = $('<li />').append($(this)); it is getting some time empty or null which i do not want tp consider. if anyone knows it how to handle this situation then share the idea. thanks

$(null) is an empty jQuery object, not null. And all objects are truthy.
If you want to test null, use this === null. You don't need jQuery for this.
However, I don't see why do you expect this to be null sometimes. Instead, it seems you want to ignore whitespace text nodes.
var $elements = $('.webgrid-footer td').contents().filter(function() {
return (this.nodeType === 3 && $.trim(this.nodeValue) !== '')
|| this.nodeType === 1;
});

$(this) will never be either null or falsey, because jQuery always returns an object reference, which is not null or falsey.
In strict mode, it's possible for this (not $(this)) to be null. In loose mode, it isn't; attempts to make this be null will cause this to be a reference to the global object.
So it may be that you want to test this, not $(this). But only in strict mode. In loose mode, bizarrely, you'd want if (this == window) to be your "null" test.
Having said that, $elements is clearly meant to be a jQuery object, and I'm not immediately thinking of a way to to create a jQuery objct with nulls in through the public API. (It's easy if you muck about with the internals...)

Related

Check if elements are part of wrapper [duplicate]

How can I check if one DOM element is a child of another DOM element? Are there any built in methods for this? For example, something like:
if (element1.hasDescendant(element2))
or
if (element2.hasParent(element1))
If not then any ideas how to do this? It also needs to be cross browser. I should also mention that the child could be nested many levels below the parent.
You should use Node.contains, since it's now standard and available in all browsers.
https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
Update: There's now a native way to achieve this. Node.contains(). Mentioned in comment and below answers as well.
Old answer:
Using the parentNode property should work. It's also pretty safe from a cross-browser standpoint. If the relationship is known to be one level deep, you could check it simply:
if (element2.parentNode == element1) { ... }
If the the child can be nested arbitrarily deep inside the parent, you could use a function similar to the following to test for the relationship:
function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
I just had to share 'mine'.
Although conceptually the same as Asaph's answer (benefiting from the same cross-browser compatibility, even IE6), it is a lot smaller and comes in handy when size is at a premium and/or when it is not needed so often.
function childOf(/*child node*/c, /*parent node*/p){ //returns boolean
while((c=c.parentNode)&&c!==p);
return !!c;
}
..or as one-liner (just 64 chars!):
function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}
and jsfiddle here.
Usage:
childOf(child, parent) returns boolean true|false.
Explanation:
while evaluates as long as the while-condition evaluates to true.
The && (AND) operator returns this boolean true/false after evaluating the left-hand side and the right-hand side, but only if the left-hand side was true (left-hand && right-hand).
The left-hand side (of &&) is: (c=c.parentNode).
This will first assign the parentNode of c to c and then the AND operator will evaluate the resulting c as a boolean.
Since parentNode returns null if there is no parent left and null is converted to false, the while-loop will correctly stop when there are no more parents.
The right-hand side (of &&) is: c!==p.
The !== comparison operator is 'not exactly equal to'. So if the child's parent isn't the parent (you specified) it evaluates to true, but if the child's parent is the parent then it evaluates to false.
So if c!==p evaluates to false, then the && operator returns false as the while-condition and the while-loop stops. (Note there is no need for a while-body and the closing ; semicolon is required.)
So when the while-loop ends, c is either a node (not null) when it found a parent OR it is null (when the loop ran through to the end without finding a match).
Thus we simply return that fact (converted as boolean value, instead of the node) with: return !!c;: the ! (NOT operator) inverts a boolean value (true becomes false and vice-versa).
!c converts c (node or null) to a boolean before it can invert that value. So adding a second ! (!!c) converts this false back to true (which is why a double !! is often used to 'convert anything to boolean').
Extra:
The function's body/payload is so small that, depending on case (like when it is not used often and appears just once in the code), one could even omit the function (wrapping) and just use the while-loop:
var a=document.getElementById('child'),
b=document.getElementById('parent'),
c;
c=a; while((c=c.parentNode)&&c!==b); //c=!!c;
if(!!c){ //`if(c)` if `c=!!c;` was used after while-loop above
//do stuff
}
instead of:
var a=document.getElementById('child'),
b=document.getElementById('parent'),
c;
function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}
c=childOf(a, b);
if(c){
//do stuff
}
Another solution that wasn't mentioned:
Example Here
var parent = document.querySelector('.parent');
if (parent.querySelector('.child') !== null) {
// .. it's a child
}
It doesn't matter whether the element is a direct child, it will work at any depth.
Alternatively, using the .contains() method:
Example Here
var parent = document.querySelector('.parent'),
child = document.querySelector('.child');
if (parent.contains(child)) {
// .. it's a child
}
You can use the contains method
var result = parent.contains(child);
or you can try to use compareDocumentPosition()
var result = nodeA.compareDocumentPosition(nodeB);
The last one is more powerful: it return a bitmask as result.
Take a look at Node#compareDocumentPosition.
function isDescendant(ancestor,descendant){
return ancestor.compareDocumentPosition(descendant) &
Node.DOCUMENT_POSITION_CONTAINS;
}
function isAncestor(descendant,ancestor){
return descendant.compareDocumentPosition(ancestor) &
Node.DOCUMENT_POSITION_CONTAINED_BY;
}
Other relationships include DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_PRECEDING, and DOCUMENT_POSITION_FOLLOWING.
Not supported in IE<=8.
I came across a wonderful piece of code to check whether or not an element is a child of another element. I have to use this because IE doesn't support the .contains element method. Hope this will help others as well.
Below is the function:
function isChildOf(childObject, containerObject) {
var returnValue = false;
var currentObject;
if (typeof containerObject === 'string') {
containerObject = document.getElementById(containerObject);
}
if (typeof childObject === 'string') {
childObject = document.getElementById(childObject);
}
currentObject = childObject.parentNode;
while (currentObject !== undefined) {
if (currentObject === document.body) {
break;
}
if (currentObject.id == containerObject.id) {
returnValue = true;
break;
}
// Move up the hierarchy
currentObject = currentObject.parentNode;
}
return returnValue;
}
Consider using closest('.selector')
It returns null if neither element nor any of its ancestors matches the selector. Alternatively returns the element which was found
try this one:
x = document.getElementById("td35");
if (x.childElementCount > 0) {
x = document.getElementById("LastRow");
x.style.display = "block";
}
else {
x = document.getElementById("LastRow");
x.style.display = "none";
}
TL;DR: a library
I advise using something like dom-helpers, written by the react team as a regular JS lib.
In their contains implementation you will see a Node#contains based implementation with a Node#compareDocumentPosition fallback.
Support for very old browsers e.g. IE <9 would not be given, which I find acceptable.
This answer incorporates the above ones, however I would advise against looping yourself.

JavaScript throws TypeError saying that my variable is undefined

I don't have much experience in JavaScript, so far I have this:
function loop() {
var authorDivs = document.getElementById('ctl00_MainContent_MCPObjectInfo_dvCreatorView').getElementsByTagName("div");
for (var i = 0; i < authorDivs.length; i++) {
var divOfDiv = authorDivs[i].getElementsByTagName("div");
if (typeof divOfDiv.item(i) === 'undefined' || divOfDiv.item(i) === null) {
console.log("This is undefined or null");
}
else {
var realDivs = divOfDiv.item(i);
realDivs.item(i).textContent = "please work plz";
}
}
}
I get the following error from the console in FireFox: TypeError: realDivs is undefined on this line: realDivs.item(i).innerHTML = "please work plz";
Essentially what I have (in my mind) is a loop that goes through authorDivs and gets all of the divs within those divs and saves them in divOfDiv. I then check to see if the divs in divOfDiv are undefined or null, if they are not then those divs get saved in a variable realDivs which I then use to edit the innerHTML. That's what I'd ideally like to see happen, what is causing the error? What am I doing wrong?
Note: I do not have access to jQuery but only JavaScript.
Edit: I've added the changes suggested below and its fixed that -- thanks! But I'm now getting the following error: TypeError: realDivs.item is not a function
What is causing that? And on another note how do I know when I'm dealing with an array and when I'm dealing with an HTMLCollection? Do you just assume? I've never used a loosely typed language before so its new to me.
Well, you'll need to move that code inside the conditional block that is supposed to prevent it! Also, || "null" is not going to work as you expect, you'll need to check for || divOfDiv.item(i) === null explicitly.
So try
for (var i = 0; i < authorDivs.length; i++) {
var divOfDiv = authorDivs[i].getElementsByTagName("div");
if (divOfDiv.item(i) == null) {
console.log("This is undefined or null");
} else {
var realDivs = divOfDiv.item(i)
realDivs.item(i).innerHTML = "please work plz";
console.log(divOfDiv.item(i));
}
}
However, that still doesn't really work for two reasons:
The i index you use to access the i-th divOfDiv comes from the iteration over authorDivs - hardly what you want. Instead, use a second loop over all divOfDivs.
Your realDivs variable does hold a single <div>, which does not have an .item method. You'd just directly access its .innerHTML property.
So you should use
var authorDivs = document.getElementById('authorView').getElementsByTagName("div");
for (var i=0; i<authorDivs.length; i++) {
var divsOfDiv = authorDivs.item(i).getElementsByTagName("div");
for (var j=0; j<divsOfDiv.length; j++) {
var realDiv = divsOfDiv.item(j);
realDiv.innerHTML = "please work plz";
console.log(realDiv);
}
}
it will happen in case when your if (typeof divOfDiv.item(i) === 'undefined' || 'null') returns true. Then you never initialize realDivs (what would happen if condition was falsy). Later you try to call item function on that unitialized object
There are two problems in the code.
comparing DOM object with 'undefined' and null. If div tag is not available in authorDivs[i], it will return empty DOM array. So, comparision of empty DOM array with undefined and null is not good approach. We can use array length property for doing validation.
divOfDiv = authorDivs[i].getElementsByTagName("div");
if(divOfDiv.length > 0) { console statement}
As item(i) is already return single DOM element, item(i) of "realDivs" variable is not proper approach. In addition to this, innerHTML method needs to be used after validating whether realDivs contains DOM element. Please update the code as below.
var realDivs = divOfDiv.item(i);
realDivs ? (realDivs.innerHTML = "please work plz"): null;
Note : item(i) will return null if DOM is not available.

Is there a way to prevent undefined javascript variables from displaying 'undefined' when inserted into html?

I am appending text which is stored in a javascript variable into a div element. The issue is that the depending on the situation there may or may not be text stored in that variable. If there is not I end up with the text 'undefined' where the valid text would have been in the div.
so as an example:
htmlelement.innerhtml = '<h2>'+array.object.title+
'</h2><p>'+array.object.textField1+
'</p><p>'+array.object.textField2+
'</p><p>'+array.object.textfield3+'</p>';
This shows up in a function which will run for each object in the array. Not all of the objects have content in all 3 text fields.
So is there an easy way to prevent 'undefined from being printed?
Right now I have this before the previous line:
if (!array.object.textfield1) {
array.object.textfield1 = ' ';
}
if (!array.object.textfield2) {
array.object.textfield2 = ' ';
}
if (!array.object.textfield3) {
array.object.textfield3 = ' ';
}
But this is not a practical solution if there are a lot of variables that need to be checked.
Can you use the logical operator || ?
array.object.textField1||''
Note: Please do take care of values like 0 or any other falsy values .
Use "The New Idiot" answer this is here just fro an extra method.
The other answer is better because it molds the check into the logic ( a good thing!) and is better for performance.
with that said REGEX!!
htmlelement.innerText = htmlelement.innerText.replace('undefined', '');
check each array item to see if its undefined with the **typeof** operator.
for each array item if the **typeof** is **undefined** you can do eather 2 things:
1. set to default
2. remove with splice()
example:
function cleanArray(theArray){
for(i=0;i < theArray.length;i++){
if(typeof theArray[i] == "undefined"){
theArray[i]="";//OR SPLICE IT OU WITH splice()
}
}
}
//NOW CALL THIS FUNCTION EVERYTIME PASSING IT THE ARRAY
cleanArray(arrayOfItems);
no simple way around this, you need to plan your design accordingly
"The New Idiot" answer is pretty good if you only have a few. If you have a more complicated object that you want to sort out, one option would be to iterate over the properties and set them to an empty string if they are undefined. e.g.
var o = {
t1: undefined,
t2: "hey"
};
for (prop in o) {
if (o.hasOwnProperty(prop) && typeof o[prop] === "undefined") {
o[prop] = "";
}
}
jsFiddle: http://jsfiddle.net/Ca6xn/

Javascript not working i put this in dom.ready in jquery

I have this code in my JS file. If i remove the the if else loops then i can get the hello as alert otherwise not.
Neither i am getting any error in firebug console
Basically in those loops i am just checking if the url contains few keywords so that ican chnage the css to selected
$(document).ready(function(){
var userPage = /child\/(.+)/.exec(location.href)[1];
if( userPage.indexOf('show') != -1 )
{$('.profile').addClass('selected');}
if( userPage.indexOf('workbook') != -1 )
{
$('.selected').removeClass('selected');
$('.workbook').addClass('selected');
}
if( userPage.indexOf('gallery') != -1 )
{
$('.selected').removeClass('selected');
$('.gallery').addClass('selected');
}
if( userPage.indexOf('mylist') != -1 )
{
$('.selected').removeClass('selected');
$('.mylist').addClass('selected');
}
if( userPage.indexOf('Photos') != -1 )
{
$('.selected').removeClass('selected');
$('.photos').addClass('selected');
}
if( userPage.indexOf('profile/list') != -1 )
{
$('.selected').removeClass('selected');
$('.list').addClass('selected');
}
alert("hillo");
The way you've set it up the alert is not inside any if statement, so it should alert no matter what. If there is no alert you're script has errors, and I spot at least two :
You're assuming the url contains the string child/, if it does not your script will halt and not work, next you're assuming the output of that exec() is an array with at least two values, selecting the second value of that array, and if for some reason your url does not contain child/ there will be no second value in that array, and the script halts, but then again it already halted in the exec().
The second error is that the document.ready function is'nt closed, thats probably just a typo.
On the other hand you should figure out a way to do this more dynamically. You're using the same class as the url string you are checking for, so for most of the cases you could just use it directly in the selector, cutting your function down to just a few lines, something like:
$(document).ready(function() {
var url = 'http://somesite.com/child/gallery'; //just a test url
var userPage = url.indexOf('child/') != -1 ? /child\/(.+)/.exec(url)[1] : null;
if (userPage) {
console.log('has child in url');
$('.selected').removeClass('selected');
$('.'+userPage).addClass('selected');
}else{
console.log('not ok');
}
});​
It returns null in the first line of your code.
var userPage = /child/(.+)/.exec(location.href)[1];
and you must get this error ": Cannot read property 'indexOf' of null"
its better to check first whether the url has child or not then proceed.

Cross-browser, javascript getAttribute() method?

trying to determine a decent, cross browser method for obtaining attributes with javascript? assume javascript library use (jQuery/Mootools/etc.) is not an option.
I've tried the following, but I frequently get "attributes" is null or not an object error when IE tries to use the "else" method. Can anyone assist?
<script type="text/javascript">
//...
getAttr: function(ele, attr) {
if (typeof ele.attributes[attr] == 'undefined'){
return ele.getAttribute(attr);
} else {
return ele.attributes[attr].nodeValue;
}
},
//...
</script>
<div>
Link
</div>
using the above html, in each browser, how do I getAttr(ele, 'href')? (assume selecting the ele node isn't an issue)
For the vast majority of cases you can simply use the built in getAttribute function.
e.g.
ele.getAttribute(attr)
According to QuirksMode this should work on all major browsers (IE >= 6 included), with a minor exception:
In IE5-7, accessing the style attribute gives an object, and accessing the onclick attribute gives an anonymous function wrapped around the actual content.
With regard to your question's update, you could try this.
It may be overkill, but if getAttribute() and the dot notation don't return a result, it iterates through the attributes object to try to find a match.
Example: http://jsfiddle.net/4ZwNs/
var funcs = {
getAttr: function(ele, attr) {
var result = (ele.getAttribute && ele.getAttribute(attr)) || null;
if( !result ) {
var attrs = ele.attributes;
var length = attrs.length;
for(var i = 0; i < length; i++)
if(attrs[i].nodeName === attr)
result = attrs[i].nodeValue;
}
return result;
}
};
var result = funcs.getAttr(el, 'hash');
It's up to you to do some cross-browser testing, though. :o)
Using ele.attributes, you need to access them by index, as in:
ele.attributes[0].nodeName; // "id" (for example)
ele.attributes[0].nodeValue; // "my_id" (for example)
Trying to pass attributes an attribute name appears to return a value whose typeof is object, so your else code is running even though ele.attributes[attr] doesn't give you the value you want.
You are trying to access properties of ele before you've established if those properties exist. Try this kind of evidence chain:
if (ele.attributes && ele.attributes[attr] && typeof ele.attributes[attr] == 'undefined')
etc.

Categories

Resources