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();
}

https://i.sstatic.net/JPqcE.png https://i.sstatic.net/HDoxn.png

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

Showcasing an HTML table using Material-UI

Currently, I have a list of issues being displayed in my browser using the material-ui code below: <Paper className={classes.root} elevation={4}> <Typography type="title" className={classes.title}> All Issues </Typography> ...

Guiding users who have disabled JavaScript through redirection

When faced with the following markup, users whose browser has JavaScript disabled will be redirected to an alternative page. This alternate page may attempt to mimic the site's functionality without JavaScript or simply display a warning message infor ...

Guide to ensuring jQuery Ajax requests are fully processed with WatiN

Currently, I am in the process of developing WatiN tests to evaluate an Ajax web application. However, I have encountered a timing issue with Ajax requests. My main objective is to ensure that WatiN waits for the Ajax request to be completed before valida ...

Removing solely the selected item, leaving the rest of the elements on the canvas untouched

Just starting out with coding and working on a game for a school project. The idea is to have random circles or "targets" appear on the screen, and the user has to click them. I've been struggling with keeping the "un-clicked" circles on the canvas wh ...

Creating a minigame using JQuery (Javascript)

I am currently developing a collection of mini-games for my big project. The approach I've taken in creating this mini-game is similar to one I used previously. However, unlike my previous version which only had one PuzzleContainer, this new iteration ...

How can I stop json_encode() from including the entire page in the JSON response when submitting a form to the same PHP script?

I only have a single index.php file in my project. I am aware that it's recommended to separate the logic from the view and use different files for PHP, JS, and HTML. This is just a test: <?php if($_SERVER["REQUEST_METHOD"] == "P ...

Utilize React Material UI to elegantly envelop your TableRows

Currently, I am faced with a challenge involving a table that utilizes Material UI and React-table. My goal is to wrap text within the TableRow element, but all my attempts have not been successful so far. Is there anyone who knows the best approach to a ...

The absence of HttpOnly Secure Cookies being transmitted

Here we go again, another inquiry regarding httpOnly Cookies. Seems like many others are facing the same predicament as me. Even though I receive the cookie from the server, it doesn't accompany other requests. I have mysite.example.com in angularj ...

Unable to display jQuery modal due to error "Uncaught DOMException: Failed to execute 'appendChild' on 'Node': The new child element contains the parent."

Check out the JS Fiddle demo here. Here is the code in question: $('#infoTable').click(infoModal); function infoModal(){ var table = "THIS IS A TABLE"; $("#dialogContainer").dialog({ appendTo: "#msg-dialog", autoOpen: f ...

Issue in Jasmine test: 'Spy should have been invoked'

I've encountered an issue while writing a Jasmine test case for the following Angular function. The test case failed with the message "Expected spy [object Object] to have been called". $scope.displayTagModelPopup = function() { var dial ...

Handling Errors with Async-Await in JavaScript: Struggling to Retrieve Error Specifics from Error Objects

Within my Node Express JS web application, there is a specific function chain present where an API function attempts to call a service function and handle any errors that may be thrown from within the service function. Located in FWBDataExtracService.js c ...

efficiently manage various nested levels of request parameters

I am configuring routes for my express app and need the following paths: /regions /regions/europe /regions/europe/france /regions/europe/france/paris Currently, I have set up individual route handlers for each path. Is there a more efficient way to ha ...

Determine whether there is text present on a webpage using JavaScript

I am familiar with Python coding from selenium import webdriver driver = webdriver.Chrome() driver.get('http://WEBSITE') assert 'TEXT' in driver.page_source However, I now require the equivalent JavaScript code. ...

What is the best way to retrieve a particular field from a Firestore Document using JavaScript?

Within my Firestore database, I have a structure of users that looks like this: The rules set up for this database are as follows: match /users/{userID} { match /public { allow read: if request.auth != null; } match /private/ ...

Gradually returning to the top with Vuetify's smooth scroll feature

Looking for a way to make the scrolling back to the top of the page smoother on my website. The button I currently have in place does the job, but it's not as smooth as I would like. Any suggestions on how to improve this? I've checked similar q ...

Display a dynamic list of data fetched from an axios Get request in a React MUI dropdown menu

import { useEffect, useState } from "react"; import Box from "@mui/material/Box"; import FormControl from "@mui/material/FormControl"; import InputLabel from "@mui/material/InputLabel"; import MenuItem from "@m ...

Erase every picture contained within the element

<div id="uniqueidhere"> <span> <span><img src="image1link"></img></span> <span><img src="image2link"></img></span> <span><img src="image3link"></img></span> <span>&l ...

Tips for injecting animation into a DIV

I am trying to make a <div> element on my webpage expand to the full width and height of the screen. While I have managed to achieve this, I also want to implement an animation that will be displayed when the <div> enlarges to fit the screen si ...

Location of chat icon in Dialogflow messenger

After successfully embedding the Dialogflow messenger in my website, I noticed that in mobile view, the chat icon is blocking the bottom navigation bar. You can refer to the screenshot here. Is there a way to reposition the chat icon higher on the page? I ...

issue with using references to manipulate the DOM of a video element in fullscreen mode

My current objective is to detect when my video tag enters fullscreen mode so I can modify attributes of that specific video ID or reference. Despite trying various methods, I have managed to log the element using my current approach. Earlier attempts with ...