Error message: "Unable to access 'title' property of an undefined value" for an item with a length of 1

Despite the fact that the collection is not undefined and the `title` attribute is also not undefined, for some reason I am unable to read the `title` attribute from the `received` variable. The error indicates that it is undefined.

var received = document.getElementsByClassName("_2her");
if (received[0].title == "Delivered") {
    chColorsForDelivered();
}

Answer №1

Your code began running before the DOM was fully loaded. Consider incorporating the 'async' attribute if you are working with HTML5.

Answer №2

To ensure that the first element is present and visible after the page has loaded, I typically employ the following technique:

window.onload = function() {
    var received = document.getElementsByClassName("_2her")[0];
    if (received.title == "Delivered") {
        chColorsForDelivered();
    }
}

Alternatively, you can utilize querySelector to target the initial instance of the specified class, which may better suit your requirements:

var received = document.querySelector("_2her");
if (received.title == "Delivered") {
    chColorsForDelivered();
}

Answer №3

let activeEl;
let bgEl;
let receivedMessages;
let rightDeliveredMsgs;
let colorChange;

window.onload = function() {
    start();
}

//=================== FUNCTIONS ===================

async function start() {
    activeEl = await document.getElementsByClassName("_2v6o");
    bgEl = document.getElementsByClassName("_673w");
    receivedMessages = await document.getElementsByClassName("_2her");
    rightDeliveredMsgs = document.getElementsByClassName("_2jnt");
    colorChange;

    bgEl[0].onmouseover = function() {clearInterv();}
    rightDeliveredMsgs[0].onclick = function() {clearDeliv();}

    //await sleep(2000);

    if (activeEl[0].innerText == "Active on Messenger") {
        changeColorsForActive();
    }
    else if (receivedMessages[0].title == "Delivered") {
        await changeColorsForDelivered();
    }
}
//for delivered
async function changeColorsForDelivered() {
    let y = 1;
    for (let i = 0; i < 6; i++) {
        changeColorsDelivered();
        await sleep(1000);
    }
}

function changeColorsDelivered() {
    let color;
    if (y === 1) {
        color = "#1e1e1e";
        y = 2;
    } else {
        color = "orange";
        y = 1;
    }

    rightDeliveredMsgs[0].style.background = color;
}
//accessories
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

I implemented the script as async. Initially, I attempted to:

  • await the variable
    receivedMessages = await document.getElementsByClassName("_2her");
    (not sufficient)
  • pause execution for 2 seconds (successful)
  • use await with the inner function (also successful). However, I am puzzled about why it works when I wait for the inner function. It doesn't seem logical to me. If I remove the await chColorsForDelivered(); await here, it throws an error stating that the title is undefined.

If this script is executed in your messenger, you will observe an orange blinking span in the conversation information section (where pictures and other content are displayed, simply remove the if) (The blinking occurs only for Delivered messages).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Disabling Javascript in Chrome (-headless) with the help of PHP Webdriver

I am experimenting with using Chrome without JavaScript enabled. I attempted to disable JavaScript by adding the --disable-javascript command line argument. I also tried some experimental options: $options->setExperimentalOption('prefs&a ...

What is causing myInterval to not be cleared properly?

const homeButton = document.getElementById('home'); window.myInterval = 0; const showHome = () => { console.log('showHome'); window.myInterval = setInterval(wait, 400) } const wait = () => { console.log('wait'); ...

Enhance communication system by optimizing MySQL, JavaScript, and PHP chat functionality

I have created a chat application using Javascript, PHP, and MySQL for two users. Every 3 seconds, it makes an AJAX request to a PHP file to retrieve messages from the database and update the page. Currently, the PHP query used is: SELECT * FROM tmessages ...

AngularJS and TypeScript encountered an error when trying to create a module because of a service issue

I offer a service: module app { export interface IOtherService { doAnotherThing(): string; } export class OtherService implements IOtherService { doAnotherThing() { return "hello."; }; } angular.mo ...

Guide on implementing react hook form 7 together with Material-UI switch

When utilizing react-hook-form with MUI switch, there is an issue where the initial value does not display on page load despite being set to true. However, upon form submission without any changes, the switches reflect their correct values (true or false). ...

Can you share tips for passing a variable from a post request to a function that accepts parameters as a string or an array of strings in Node.js?

I am struggling to insert the variable named query into the end of the prompt. I attempted to use template literals but it was unsuccessful. (async () => { const gbtResponse = await openai.createCompletion({ model: "text-davinci-002", prompt ...

Please provide several input fields with identical 'name' attributes for submission

I'm encountering an issue with a form where multiple input fields (text) share the same name attribute. On the backend, I am utilizing node.js and Mongoose for a POST method. Below is a snippet of the code: if(existingFruit) { Fruit.findOneA ...

What are the reasons behind the jQuery file upload failing to work after the initial upload?

I am currently utilizing the jQuery File Upload plugin. To achieve this, I have hidden the file input and set it to activate upon clicking a separate button. You can view an example of this setup on this fiddle. Here is the HTML code snippet: <div> ...

Adjust the Container's gutters in MaterialUI according to screen sizes

I am trying to adjust the gutters for different screen sizes in my project. I want to turn off the gutters for xs, sm, and md, but have them enabled at xl and larger. Despite following the API documentation, it doesn't seem to be working as expected. ...

What is the best way to retrieve the ID of the list item that has been clicked during a button event?

How can I use jQuery to get the ID of a selected list item when clicking a button in my HTML code? <ul id="nav"> <li><a href="#" rel="css/default.css" id="default" > <div class="r1"></div> </a>< ...

Having trouble with Ajax.updater?

I am a JavaScript newcomer and currently facing an issue with prototypes. I am attempting to update sample.jsp using Ajax.updater after it is loaded, but for some reason, it's not working. Here is the source code of sample.jsp: <%@page contentTyp ...

modifying output of data when onchange event is triggered

I am struggling with creating an onchange event for my option box in which the users of a site are listed. I have two input boxes designated for wins and losses, but the output is not changing when I select a user from the list. What could be wrong with my ...

What is the best way to choose the initial element in every group using jQuery?

If we have the following HTML input: <p>A</p> <p>B</p> <p>C</p> <div>D</div> <p>E</p> <p>F</p> <p>G</p> We can select B, C, F and G using the following code: $('p + ...

Exploring the array mapping technique in React with nested objects

As part of a school project, I am working on creating a dashboard to visualize some data. I have successfully loaded the data into the front end using React. Now my goal is to retrieve specific values from a large array. However, I am uncertain about how ...

Combining JSON objects in Node.js

I am extracting data from my database and converting it to JSON format. However, I now want to merge all the JSON data into a single JSON object. I have attempted various methods, but due to my limited knowledge of JavaScript syntax, I have not been able ...

The type string[] cannot be assigned to type 'IntrinsicAttributes & string[]'

I'm attempting to pass the prop of todos just like in this codesandbox, but encountering an error: Type '{ todos: string[]; }' is not assignable to type 'IntrinsicAttributes & string[]'. Property 'todos' does not ex ...

Error message encountered in React Material-UI while attempting to run the basic Hello World test - Invalid hook call

My plan is to kick off a project using React and Material-UI. I decided to start with the simplest Hello World example based on the official documentation, in a brand new Ubuntu OS. However, when I tried running the code, an error popped up! Here's wh ...

Tips for sending an Ajax request to a separate URL on the same server

When making an ajax request to my server, I use the following code: var data = ''; $.ajax({ type: 'GET', url: 'api/getnews/home/post/'+title, data: data, datatype: 'json', success: f ...

Here's a guide on how to package and send values in ReactJs bundles

I'm currently involved in a ReactJs project that does not rely on any API for data management. For bundling the React APP, we are using Webpack in the project. The challenge now is to make the React APP usable on any website by simply including the ...

Anomalous Snackbar and Alert Interactions

Why am I getting an error with this code snippet: import Snackbar from "@mui/material/Snackbar"; import MuiAlert from "@mui/material/Alert"; const Alert = ({children}) => <MuiAlert>{children}</MuiAlert> <Snackbar ope ...