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

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.

Related

Why does my if statement work with an else if, but not an OR operator

I wrote a small piece of JS in the console, to loop through recommended connections on LinkedIn and if the text contains a certain word, ignore that card, otherwise click the 'X' close button.
Initially I wrote it like this:
const list = document.querySelector('.mn-pymk-list__cards');
const cards = list.querySelectorAll('.mn-pymk-list__card');
cards.forEach( (card, i) => {
setTimeout( ()=>{
let text = card.querySelector('.member-insights__count');
if( !text.textContent.includes('Sharon') || text === null ) {
card.querySelector('.pymk-card__close-btn').click();
} else {
card.style.background = 'green';
}
}, i * 1000 )
});
However, when it ran, it would sometimes error (whilst continuing to iterate) with 'Could not read textContent of null'.
However, when I wrote the code like this:
const list = document.querySelector('.mn-pymk-list__cards');
const cards = list.querySelectorAll('.mn-pymk-list__card');
cards.forEach( (card, i) => {
setTimeout( ()=>{
let text = card.querySelector('.member-insights__count');
if( text === null ) {
card.querySelector('.pymk-card__close-btn').click();
} else if (!text.textContent.includes('Sharon')) {
card.querySelector('.pymk-card__close-btn').click();
} else {
card.style.background = 'green';
}
}, i * 1000 )
});
It runs absolutely fine and does what I want it to.
QUESTION: I can't understand why the first option doesn't work, as it seems more concise and theoretically should do the same thing?
I suspect it has something to do with the fact that on LinkedIn, some of the suggested contacts don't have a class of '.member-insights__count' and instead have '.member-insights__info'.
But, that should still make text resolve to null, right?
Any insight would be great!
if( !text.textContent.includes('Sharon') || text === null ) {
What would you expect this code to do when text is null? It will crash because you can't access properties or methods of null.
You need to check for null first.
if( text === null || !text.textContent.includes('Sharon') ) {
If textContent is null (e.g. as you said, the contact has '.member-insights__info' instead), !text.textContent.includes('Sharon') will cause the error message.
In the second version, that line can only be reached if the text isn't null.
The || operator will only evaluate the 2nd argument if the first argument is false.
In your case the only difference between the first and second code snippets is the order in which you check if the value is null
What you need to do is check for null first like this:
if( text === null || !text.textContent.includes('Sharon')) {
This way it will only check if text includes specific text once it's determined that text is not null

Javascript variable is null but goes in if-statement

I have a bit of a weird problem. I TRIED to create a jsfiddle but I don't get the same result so I'm sorry I can't share more of what I have.
var parent = id && Number(oldParent) !== 1 ? $('#main_container #item_' + itemId).parent().parent().prev() : null;
This is how I get the parent. It should be null when it isn't needed.
Later, I get this check in the same function:
if (parent && parent != null && !parent.hasClass('.main-group'));
{
console.log(parent == null);
var siblingCount = parent.next().children().length;
if (siblingCount === 0)
{
parent.removeClass('group');
parent.addClass('normal-item');
}
}
So, I check if parent is set (just in case), parent is not null and parent doesn't have the class main-group. This should work, at least I thought, but I get the error:
TypeError: parent is null
On this row:
var siblingCount = parent.next().children().length;
So, that's why I added the console log to see if parent is null. Guess what? The console.log says true. This means parent is equal to null, but it still goes IN the if-statement. I use && so it shouldn't go in the if statement because already one operation is false.
I had others look at it and they couldn't figure it out either.
There is a semicolan at the end which is making it to execute as the statement is terminated and next statement executes.
var parent = null;
if (parent && parent != null && !parent.hasClass('.main-group'));{
alert("Hello");
}
For Debin comment:
var parent = null;
if (parent != null); { alert("Vinoth") }
// The above one is equivalent:
if (parent != null) do nothing ;
alert ("hi");
JavaScript thinks that you have an empty statement and everything to right of it is treated as no longer belonging to the if condition and thus an independent one making it to execute.
You have a ";" at the end of this line
if (parent && parent != null && !parent.hasClass('.main-group'));
This is what is causing the problem.

How to capture null in 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...)

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.

Checking textbox if it's empty in Javascript

I wrote a simple html file with a textbox and submit button, and it generates and document.write's a response dependant on what you submit. I want to have it generate a response saying to enter content if the box is empty. The textbox's id is chatinput, so I have the following the code in the beginning
var chatinput_box=document.getElementById('chatinput');
var chatinput=chatinput_box.value;
Then a have a conditional, although I can't get it to work correctly; I've tried
if(chatinput==""){}
if(chatinput.length=0){}
if(chatinput=null){}
and others but none have worked correctly. Does anyone have another idea?
It should be this:
var chatinput = document.getElementById("chatinput").value;
if (chatinput == "" || chatinput.length == 0 || chatinput == null)
{
// Invalid... Box is empty
}
Or shorthanded:
if (!document.getElementById("chatinput").value)
{
// Invalid... Box is empty
}
The = assigns a value whereas == checks whether the values are equal.
Just offering an alternative, not trying to steal thunder ...
Create an isEmpty function to reuse on a variety of items.
function isEmpty(val){
return ((val !== '') && (val !== undefined) && (val.length > 0) && (val !== null));
}
Then you can apply it to whatever element you want:
if(!isEmpty(chatinput)){
// hooray its got a value!
}
Not exactly original, its the concept stolen from PHP, but it comes in handy a lot.

Categories

Resources