Empty element and getElementsByClassName - javascript

I try to parse site and i have problem. When i parse table with empty element
type = elements[i].getElementsByClassName("listing-item__type");
I have this
VM56462:7 Uncaught TypeError: Cannot read property 'innerText' of undefined
at <anonymous>:7:25
How to fix it? Is it possible to check the element for empty?

Because getElementsByClassName return an array, you can not treat array as DOM element, you need get index and use
if (type[0] != undefined && type[0].innerText){
// add code here
}

Without seeing your HTML structure, you can check the presence of an element through:
if (type) {
// "type" is not undefined
}
Please note also that your "type" will return an array of elements (since you're using getElementsByClassName). Access the first one and check it is truthy before checking for the .innerText.

Related

how to access js object properties?

I'm lost on how to get object properties in JS. I'm getting values from firebase and I wanted to filter the result by its id:
//id is from query params (selecting 1 item from view)
const snippet = snippets.filter(snips => {
if(snips.id == id) return snips;
})
If I console.log after these lines, I'm getting this:
const obj = snippet[0];
So I tried to get properties by using snippet[0] which returns this:
But if I try to get properties such as:
console.log(obj['id']);
//console.log(obj.title); - tried this as well
it returns:
Entering data:
This isn't how the array::filter function works. It iterates over the array and the callback returns a boolean true/false if the element should be returned in the result array.
const snippet = snippets.filter(snips => snips.id == id)
Issue
Cannot read property "title" of undefined
This is saying that snippet[0] is currently undefined when trying to access any properties
snippet[0].title, a root title property also doesn't exist in your other console log
Solution
Your snippet is (possibly) an array of 1 (or 0) element, so in order to access the title nested in data property
snippet[0].data.title
And in the case that the array is empty or has an element without a data property, use optional chaining or guard clauses to check the access
snippet[0]?.data?.title
or
snippet[0] && snippet[0].data && snippet[0].data.title
looking at what you are asking you need to enter first the data.
console.log(obj[0].data.content)

Precaution needed while using variable.length in javascript for array and object?

I want to use javascript length property (variable.length) to find the length of an array or object.
Is there any special check required before using the length property for an array or object.
Different types of errors are found while using the length property in my previous experience. So I need to know the correct way to use the length property and possible errors while using length property.
You need check if the array is different to undefined or null, after that, you can get the length property. Also you can use Array.isArray() to check if is array the variable
isArray reference
You can access every property (also the "length") property on everything, except on null and undefined. In most cases .length is undefined then though.
The length attribute can be found in multiple data structures.
The length in String.prototype.length or in Array.length.
For any variable, you should check whether the variable itself exists first and then check the length if you know that it will have length attribute like for arrays.
// This will be applicable for data structures with length attribute
if (variable && variable.length) {}
// If you don't know the data structure
if (('length' in variable) && (variable.length >= some_num)) {}

Inconsistant JavaScript Return Values

Why does getElementById() return null if the ID doesn't exist and getElementsByClassName() returns undefined if the class doesn't exist? This seems like an inconsistency in the JavaScript language since both are DOM methods. For example:
console.log( document.getElementById('bogusID') ); // null
console.log( document.getElementsByClassName('bogusClass')[0] ); // undefined
I recently had to find out the hard way, having my program crash since I wrongly assumed both methods would return "undefined" on a fail.
Is there actually a reason for the different return values?
document.getElementsByClassName('bogusClass') returns an empty array and you are trying to access the zeroth element, which doesn't exist, so you get undefined.
Javascript, unlike other programming language doesn't throw index out of range exception, because indexes are implemented as properties and accessing a property which doesn't exists returns undefined.
In terms of checking and handling for null and undefined, both are falsy value in javascript and hence your code should be the same for both cases.
if(condition){
// Both undefined and null would not pass the condition.
}
console.log( document.getElementById('bogusID') ); // null
Thats because there aren't bogusID items on your DOM so the return is null
console.log( document.getElementsByClassName('bogusClass')[0] ); // undefined
Thats because your getting the index 0 of an array that doesn't have an element at the 0 pointer. So the index 0 of the array isn't defined (undefined)
I don't know how the program is defined internally for getElementById() & getElementByClass but according to mozilla documentation getElementById() basically returns a reference(object) to the element.
ID
eg: element = document.getElementById()
Return Value
element -
is a reference to an Element object, or null if an element with the specified ID is not in the document. In dom there should be only 1 ID with a same name so there is no reuse in ID name.
Class
eg: var elements = element.getElementsByClassName(names);
getElementsByClassName() method returns a live HTMLCollection containing all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node.
In dom there should be only 1 ID with a same name so there is no reuse in ID name and also HTMLCollection uses array to collect all the elements that are refered using classname.
Undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value.
Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Get object property value

I have an object that contains an array of objects from which I need to get a value of their properties.
As an example this is what I need to get:
Stronghold.bins.models[0].attributes.entity.title
Which returns "Stronghold Title 1"
function grabItemName(){
var itemName=$(Stronghold.bins).each(function(){
return this.models[0].attributes.entity.title == title;
console.log(itemName);
})
};
(if there is a better way for me to ask this question please let me know)
I apologize if this was poorly asked!
The current issue is that it does not understand the array value '[0]' and cannot read it as it is undefined. What do I need to do to grab the 'title' value of all items in the array?
What do I need to do to grab the 'title' value of all items in the array?
That's what .map [docs] is for. It lets you map each value in an array to another value.
In the following I assume you want to iterate over each Stronghold.bins.models, because iterating over Stronghold.bins does not make sense with the provided information:
var titles = $.map(Stronghold.bins.models, function(obj) {
return obj.attributes.entity.title;
});
// `titles` is now an array containing `.attributes.entity.title;` of
// each object.
The current issue is that it does not understand the array value '[0]' and cannot read it as it is undefined.
Well, that won't happend anymore ;) In your example you where iterating over the properties of the Stronghold.bins object. One of these properties is models itself (!) and I doubt that any other property value has a models property.
Try using the other version of the each function:
$.each(Stronghold.bins, function () {
});
The version you are using is for looping through an element on the page, e.g $('body div p').each(function() {}), which isn't what you want in this instance: You want to loop over the values contained in Stronghold.bins.

OOO javascript: object self reference returns undefined but console shows it exists

Okay, so I did search a bit before posting... no luck (or maybe I'm just stupid).
I have this array I call "myArray" and I push objects onto it to populate some variables:
myArray.push({
time : (y.moveTime - y.startTime),
pos : y.move,
last : myArray[y.recents.length-1].time
});
My issue is why does firebug complain about the "last" variable: "Uncaught TypeError: Cannot read property 'time' of undefined". If I do
last : myArray[y.recents.length-1]
everything is fine.
An observation I don't understand:
The array is empty when I have the ".time" reference, but if I remove it, the array is full.
What am I missing here? I don't get it :(
Thanks for any pointers.
The error means that the evaluated value of
myArray[y.recents.length-1]
is not an object that has a time property. This likely occurs when you perform the first push because the array does not yet have any elements.
If you want to hide the error and just assign the last property to undefined in this case, you can just add a fallback value:
last: (myArray[y.recents.length - 1] || {}).time
The value of myArray[y.recents.length-1] can be anything (some string, object, array, null etc.). you can set the value of last with it and will not make any error.
however, if you set a property to a non-object (like setting time), it will cause an error.

Categories