Measuring the variable size of an array containing objects of a given class

Recently, I created a basic code/userscript to receive notifications about any changes on a specific website:

function notifier(){
  setTimeout(function () {       
    location.reload(true); 
  },60000)   
}

function notiCounter() {
    console.log("Counting notifications");
    var noti = document.getElementsByClassName("notification");
    for(var i = 0; i < 2; i++) {
        if(noti[i].innerHTML != undefined) {
            console.log(noti[i].innerHTML);
            notifications++;
            console.log("Notifications: " + notifications);
        }
    }
}

function notification(){ 
    setTimeout(function () {
        notiCounter();
        if(notifications > 0){
          document.title = "(" + notifications + ") new notifcations";
          sound.play();
          }
    notifier();
     },50)
}

notification();

However, the issue arises with the dynamic nature of the final number of noti[i], which keeps changing. If I replace i < 2 with a higher number, the loop turns into an infinite one. On the other hand, setting it too low (like 2), means that data might be lost if the actual number goes beyond 2.

Do you have any suggestions to address this problem? It's probably quite obvious, but sometimes things tend to get blurry when working late at night!

Answer №1

Instead of verifying if i < 2, consider checking if i < noti.length. Alternatively, you can cycle through utilizing a loop like for(var i in noti). Even better, if you solely need the count of notifications, simply access the value in noti.length

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

Do you only need to utilize Provider once?

When using the redux module in react-native, it is common practice to utilize createStore from 'redux'. I am curious, is it sufficient to use <Provider/> just once to make the Redux store accessible throughout our app? import ReactDOM from ...

Iterating through a series of AJAX requests in JavaScript until the variable equals "No" and then terminating the loop

After dedicating the past two days to my work, I am still struggling to find a solution. Any assistance would be greatly appreciated. My current setup involves nodejs and Vue. I need help figuring out how to break out of an AJAX call when receiving a "No" ...

Is it possible to automate a query to an API through PHP and store the results on a local drive?

Recently, I created a webpage that fetches data from an API. However, the response time from the server is quite slow, taking around 10-20 seconds to retrieve the information. To mitigate cross-domain issues, I have set up a PHP proxy for the JavaScript re ...

Having trouble accessing object properties fetched via API, receiving the error message "TypeError: Cannot read property '' of undefined" in Next.js with JavaScript

Encountering a unique issue specific to NextJs. Fetching data from an API using a custom hook and receiving an array of objects as the result. Successfully logging the entire result (array of objects). const myMovieGenreObjects = useFetchNavBarCategories( ...

Styling text using CSS depending on the displayed text

Utilizing Awesome Tables (AT), I am extracting data from a Google Sheets document to display on a website. The HTML template in the sheets is used for formatting the data, specifically focusing on the table output with inline CSS styling. Since the templat ...

Align elements on the left side with some space between them

Having trouble displaying a list of images inline within a div. When I float them left, they leave a lot of space and do not display properly. Can anyone help me with this issue? See screenshot below: Here is my html code: <div class="col75"> & ...

Minimizing the gap between icon and label text

I have a React form that I need help with. The issue is that I want to reduce the space between the list icon and the label. Here is the CSS I am using: .form__container { display: flex; flex-wrap: wrap; } .form__container input { color: rgb(115, 0, ...

Improving User Experience with HTML Form Currency Field: Automatically Formatting Currency to 2 Decimal Places and Setting Maximum Length

Hello there, I am currently facing an issue with the currency auto-formatting in a deposit field on my form. The formatting adds 2 decimal places (for example, when a user types 2500, the field displays 25.00). However, the script I wrote does not seem to ...

Is it possible to integrate a backbone model with Angular?

Below is an example of a Backbone post model: var Post = Backbone.AssociatedModel.extend({ urlRoot: ApiService.resolveRESTUrl('posts'), defaults: { age : 0, fname : "", lname : "", manager : null }, ...

Utilizing jQuery/Ajax to send an ID parameter to a PHP script

This code is where the user interacts. <html> <head> <title></title> <script src="jquery-1.9.1.js"></script> <script src="jquery.form.js"></script> </head> <body> <?php include 'con ...

AngularJS - retrieving and displaying the selected value from an HTML dropdown menu

Could someone help me figure out why the Land selection is empty when trying to display it as {{ selectCenter.land }}? For reference, here is a functional plunker: http://plnkr.co/edit/Q8jhdJltlh14oBBLeHJ9?p=preview And the relevant code snippet: ...

The system is unable to locate the module at 'C:UsersSanjaiAppDataRoaming pm ode_modulesprotractorinprotractor'. This error originates from internal/modules/cjs/loader.js at line 960

After running "protractor conf.js" without any issues, I decided to install protractor globally using the command "npm install -g protractor". However, after installing protractor globally, I encountered the following error message: internal/modules/cjs/lo ...

Express: Every declaration of 'user' must have the same modifiers

In my application, I am utilizing both express and passport. Within these packages, there is a user attribute within the Request interface. Currently, the express package has a user attribute in the request object, such as req.user, but no additional prope ...

Sped up object outpacing the mouse pointer

I'm currently developing a drag and drop minigame, but I've encountered an issue with the touch functionality. The draggable function (using only cursor) works flawlessly, however, when I tried to implement touch support for mobile and tablet use ...

"Enhance the functionality of material-table by incorporating a multi-select feature

My data management has been made easier with Material-Table, but I have encountered a small issue. The code below shows how I currently get a select menu for my data. However, I am looking to have a multiselect menu instead, allowing me to save more than o ...

What is the best way to retrieve a nested item from a JSON array within another array using React Native?

I'm working on fetching a Json array in React Native. Currently, I can retrieve data like "name" and "availability" but I'm facing an issue returning the "url" within the media.data array. { "data": [ { "id": 2, ...

Display a pop-up window upon clicking anywhere on the webpage using jQuery and HTML

Is it possible for me to create a pop-up window that opens a specific website when a user clicks anywhere on the page, similar to pop-up companies? Can this be achieved using HTML, JavaScript, and jQuery? Any help would be greatly appreciated. ...

Issue with Alignment of Border in PDF [Example Included]

I am currently developing a straightforward react application with very minimal content. index.js: <div className="App"> <div id="printable-div"> <h1>Generate PDF</h1> <p>Capture a screenshot of ...

What is the process for animating classes instead of ids in CSS?

My webpage currently features a setup similar to this. function wiggle(){ var parent = document.getElementById("wiggle"); var string = parent.innerHTML; parent.innerHTML = ""; string.split(""); var i = 0, length = string.length; for (i; i ...

Retrieve dynamic data from a website using jQuery's AJAX functionality

I am trying to retrieve the data from example.com/page.html. When I view the content of page.html using Chrome Browser, it looks like this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> & ...