Javascript Length Undefined or Zero - javascript

I am trying to write a Javascript function that returns a single element given the name. I found this question and modified the answer to use the ternary operator.
function getField(fieldName)
{
var elements = document.getElementsByName(fieldName);
return elements.length && elements.legth > 0 ? elements[0] : null;
}
My question is about the case where document.getElementsByName(fieldName) doesn't find any matches. Does it return undefined or 0? When I output elements.length as an alert message, the value in the alert is 0 but the console Chrome's DevTools says undefined. When I call console.log(elements.length) from the console, it ouputs 0 and undefined.
I know that my function handles either case, but what am I missing here? What is Javascript actually doing?
Thanks in advance for helping me understand this.
EDIT: Sorry for posting a picture instead of actual code and thanks for the syntax clarification.

As your question seems to be what document.getElementsByName is returning when it isn't found, it would be an empty NodeList, with a length of 0 (so not undefined)
Therefor, the easiest would be as dandavis suggested in his comment to simply return the first element of the nodelist. If it is empty, it will be undefined, if not it would the first element (not sure if that always matches your case though)
so your function might as well be
function getFieldAt(fieldName, index = 0) {
return document.getElementsByName(fieldName)[index];
}
if you don't use optional parameters, you could change it to
function getFieldAt(fieldName, index) {
return document.getElementsByName(fieldName)[index || 0];
}
Your misunderstanding about the devtools are thoroughly explained in the comments and the other answer as well :)

elements.length is equal to 0 in your case.
Your understanding of console.log is misleading:
console.log(elements.length);
> elements.length is printed. It evaluates to 0, so 0 is printed
> console.log(elements.length). It evaluates to undefined, so undefined is printed.

no need to test length value simply use:
function getField(fieldName)
{
let elements = document.getElementsByName(fieldName);
return (elements[0]) ? elements[0] : null;
}
console.log( getField('div-A') );
console.log( getField('neverExist') );
<div name="div-A"> div-A 1 </div>
<div name="div-A"> div-A 2 </div>
<div name="div-A"> div-A 3 </div>

Related

Not able to compare strings in Javascript

I am trying to compare a string with a set of strings stored in an array. Here is the block of code:
then(op => {
if (op[0].probability > FILTER_THRESHOLD) {
if (FILTER_LIST.indexOf(op[0].className) > 1) {
console.log("EUREKA! EUREKA! EUREKA!")
console.log(op[0].className)
return true;
}
}
return false;
})
The second if statement should evaluate to true in some cases but it is not. The return is always false.
op[0].className should be a string and I am also able to get the value from op[0].probability correctly.
What could be the reason?
I have tried debugging and cannot seem to get why the 'if' statement is not being true.
Here is the FILTER_LIST array:
var FILTER_LIST = ["Hello", "Please", "Simple"];
Please advise how I can fix this!
Thank you!
indexOf(...) > 1 asks "did it find a match at the third element or later?" You'll get false if it matched at index 0 or 1. If you want just "it found one anywhere", you want !== -1, >= 0, or to use includes instead of indexOf.
if (FILTER_LIST.indexOf(op[0].className) !== -1) {
// or
if (FILTER_LIST.indexOf(op[0].className) >= 0) {
// or
if (FILTER_LIST.includes(op[0].className)) {

find IP addresses not in array

I have a list of /24 IP addresses in an array called subRet
subRet's values are like
10.0.0.1
10.0.0.2
10.0.0.50
10.0.0.80
What I want is a list of IP address that are NOT in the array.
What I've tried is this:
var test=['10.0.0.1','10.0.0.103','10.0.0.111','10.0.0.131','10.0.0.198'];
for(i=1;i<=254;i++){
if( ! $.inArray('10.0.0.'+i.toString(), test ) ) {
console.log("adding "+'10.0.0.'+i.toString());
}
}
Console log says
adding 10.0.0.1
What I want is a list if IP's that are not in the list, like 10.0.0.2.
how?
First, you're not declaring the variable i anywhere, which is bad practice as the scope will likely not be what you expect. Secondly, no need for jQuery here, you can use vanilla ES6. Third, no need to call i.toString as you're concatenating it to a string already, which performs implicit casting.
var test=['10.0.0.1','10.0.0.103','10.0.0.111','10.0.0.131','10.0.0.198'];
for(let i = 1; i <= 254; i++){
if(!test.includes('10.0.0.' + i)) {
console.log("adding 10.0.0." + i);
}
}
The issue of your code is in the way you check the result of the method inArray, since inArray method retrieves the index of the tested IP in the array, and when it finds nothing it returns -1. So you need to make sure that the returned index is higher than -1:
if( ! $.inArray('10.0.0.'+i.toString(), test ) > -1)
Read more about inArray
this worked
var test=['10.0.0.1','10.0.0.103','10.0.0.111','10.0.0.131','10.0.0.198'];
for(i=1;i<=254;i++){
if( ! test.includes('10.0.0.'+i.toString()) ) {
console.log("adding "+'10.0.0.'+i.toString());
}
}

How can I set a localStorage value to the number 1 if nothing is returned?

Here is what I have tried so far:
this.phrasesOrderById =
parseInt(storage.getItem('phrasesOrderById').toInt(),10) || 1;
However this gives me a message saying cannot read property toInt of null.
Can someone give me some advice on how I can set the value to 1 if a null is returned from getItem? Note that I spread this one line across two as it doesn't seem to display properly when it's just one line.
following works
phrasesOrderById = parseInt(localStorage.getItem("phrasesOrderById") || 1);
you can use the ? : (conditional) operator in JavaScript
this.phrasesOrderById = storage.getItem('phrasesOrderById')?parseInt(storage.getItem('phrasesOrderById').toInt(),10):1;
Or you can simply use If/Else
if(storage.getItem('phrasesOrderById') {
this.phrasesOrderById = parseInt(storage.getItem('phrasesOrderById').toInt(), 10);
}
else{
this.phrasesOrderById = 1;
}

javascript conditional not reaching else

I'm working on creating a toggle function to 'favorite' an item from a list of many. I've got working script to toggle the item in and out of a user-specific favorites list, communicate that change to a database, and populate the rest of the site accordingly. That all works fine, it's mostly PHP and Ajax.
However, my javascript is ass. I'm stuck on a conditional to change the icon from a filled heart to an empty one. For some reason it never reaches the else statement even when the if statement is false. If I reverse the conditions, it still handles the if fine but never the else.
the image is:
<img src="includes/icons/fave-<?php echo $favStatus; ?>.png" id="faveToggle" class="faveIcon" onClick="toggleFave()">
the conditional, located in toggleFave() is:
if(document.getElementById('faveToggle').src.toString().indexOf("fave-false.png")){
document.getElementById('faveToggle').src = "includes/icons/fave-true.png";
} else {
document.getElementById('faveToggle').src = "includes/icons/fave-false.png";
}
So, uhh, whuddo I do?
indexOf returns the 0-based index of where the substring is found, or -1 if not. -1 happens to be "truthy".
That means you have two possibilities, it's either in the string and has a positive (truthy) position, or it's not and you get a truthy -1. Either way, it will always go into the first block. You want:
if(document.getElementById('faveToggle').src.toString().indexOf("fave-false.png") > 0){
You only need to fetch the element once:
var toggle = document.getElementById("faveToggle");
if (toggle.src.indexOf("fave-false.png") >= 0) {
toggle.src = "includes/icons/fave-true.png";
}
else {
toggle.src = "includes/icons/fave-false.png";
}
The .indexOf() function returns the position of the searched-for substring, or -1 if it isn't found.
You can checkif it is greater than -1
if(document.getElementById('faveToggle').src.toString().indexOf("fave-false.png")>-1){
alert('1')
document.getElementById('faveToggle').src = "includes/icons/fave-true.png";
} else {
alert("2")
document.getElementById('faveToggle').src = "includes/icons/fave-false.png";
}
jsfiddle
Here's my simplified version using a ternary operator:
var toggle = document.getElementById('faveToggle'),
newState = toggle.src.toString().indexOf("fave-false.png") == -1 ? true : false;
toggle.src = "includes/icons/fave-"+newState+".png";
You can use the bitwise not ~ operator for checking.
~ is a bitwise not operator. It is perfect for use with indexOf(), because indexOf returns if found the index 0 ... n and if not -1:
value ~value boolean
-1 => 0 => false
0 => -1 => true
1 => -2 => true
2 => -3 => true
and so on
if(~document.getElementById('faveToggle').src.toString().indexOf("fave-false.png")){

How to use IndexOf in JQuery

if($('#this').val().indexOf('4289')){
Do something
else
Do something.
This works only with that 4289,
When I try to add other numbers to be indexed next to it using 'or', it doesn't work. How should I put other number. E.g
IndexOf('4289||78843')
I want this to check this numbers and if the number in the input field is not one of this, to echo error.
Here's more which happens to die when one revisits the field.
$('#Zip').blur(function(){
if (($(this).val().indexOf('0860') > -1)||($(this).val().indexOf('0850') > -1)){
$('#Status_Zip').html("No way.")
$(this).alterClass('*_*', 'Success')
return false;
}else{$('#Status_Code').hide()
$(this).alterClass('*_*', 'Error')
$(this).css('border-color', '#F00').css('background-color', '#FFC').effect("pulsate",{times:4},2)
return true;
}
})
That's because it would be looking for the string '4289||78843', which doesn't exist in the target I'm assuming. Logical operators can't just be tossed in anywhere, only where there are actual values to logically operate on. Something like this:
if(($('#this').val().indexOf('4289') > -1) ||
($('#this').val().indexOf('78843') > -1))
The return value of the indexOf() function is the numeric index of that value in the target value, or -1 if it's not found. So for each value that you're looking for, you'd want to check if it's index is > -1 (which means it's found in the string). Take that whole condition and || it with another condition, and that's a logical operation.
Edit: Regarding your comment, if you want to abstract this into something a little cleaner and more generic you might extract it into its own function which iterates over a collection of strings and returns true if any of them are in the target string. Maybe something like this:
function isAnyValueIn(target, values) {
for (var i = 0; i < values.length; i++) {
if (target.indexOf(values[i]) > -1) {
return true;
}
}
return false;
}
There may even be a more elegant way to do that with .forEach() on the array, but this at least demonstrates the idea. Then elsewhere in the code you'd build the array of values and call the function:
var values = ['4289', '78843'];
var target = $('#this').val();
if (isAnyValueIn(target, values)) {
// At least one value is in the target string
}

Categories