Not able to make a SignUP request on app deployed on Heroku & Netlify

I am facing an error while making the POST SignUp request.

I had deployed the frontend on Netlify here and the backend on Heroku here.

Error

I am getting 2 errors:

  1. I am getting

     `users.findOne()` buffering timed out after 10000ms
    
  2. I am getting this on console

      SyntaxError: Unexpected token i in JSON at position 0
    

enrror

Code

Attached is the code in the flow

index.js

const connectToMongo = require('./db');
const express = require('express');


connectToMongo();
var cors = require('cors')
const app = express()
// const port = 5000

//to use req body 
app.use(cors())
app.use(express.json())

//Available routes
app.use('/api/auth',require('./routes/auth'));
app.use('/api/notes',require('./routes/notes'));

app.listen(process.env.PORT  , () => {
  console.log(`my-notebook backend listening at https://my-notebook-mohit.herokuapp.com:${process.env.PORT }`)
})

auth.js (see only route1)

const express = require("express");
const { body, validationResult } = require("express-validator");
const router = express.Router();
const User = require("../models/User");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const JWT_SECRET = "mohitisagood$boy";
const fecthUser = require("../middleware/fetchUser");

//ROUTE 1 :Creating a User :POST - "/api/auth/createuser"
router.post(
  "/createuser",
  [
    body("name", "Name must have at least 3 characters").isLength({ min: 3 }),
    body("email", "Enter a valid email").isEmail(),
  ],
  async (req, res) => {

    let success = false;
    //If there are errors, then return bad request + Errors
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({success, errors: errors.array() });
    }

    try {
      //Check whether email exists
      let user = await User.findOne({ email: req.body.email });
      //console.log("user.nemail = " + user);
      if (user) {
        //console.log(user.email);
        return res.status(400).json({success, error: "Email Already Taken" });
      }

      //hashing the password here
      const salt = await bcrypt.genSalt(10);
      const secPass = await bcrypt.hash(req.body.password, salt);
      //user is created
      user = await User.create({
        name: req.body.name,
        email: req.body.email,
        password: secPass,
      });

      //passing the id as data to make jwt token
      const data = {
        user: {
          id: user.id,
        },
      };

      const authToken = jwt.sign(data, JWT_SECRET);
      //console.log(authToken)

      
      success = true;
      //res.json(user);
      res.json({success, authToken });
    } catch (error) {
      console.log(error.message);
      res.status(500).send("internal server error");
    }
  }
);

//ROUTE 2 :Authenticating a User :POST - "/api/auth/login"
router.post(
  "/login",
   .......
    )
});

module.exports = router;


MODEL_SCHEMA – users

const mongoose = require("mongoose");
const { Schema } = mongoose;

const UserSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
    validate(value) {
      if(value.length < 5) {
        throw new Error( "Minimum length is 5 characters");
      }
      else if (!value.match(/d/) || !value.match(/[a-zA-Z]/) ) {
        throw new Error(
          "Password must contain at least one letter and one number"
        );
      }

    }
    
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

const User = mongoose.model("users", UserSchema);
module.exports = User;

SignUpPage.js (frontEnd)

import React,{useState} from 'react';
import { useHistory } from 'react-router-dom';
import imgpath from "../assets/notepic.jpg";
import { motion } from 'framer-motion';

const Signup = (props) => {

    let history = useHistory();

    const [credentials, setCredentials] = useState({name:"", email:"", password:"",confmpassword:""});

    const onChange = (e) => {
        setCredentials({ ...credentials, [e.target.name]: e.target.value });
        //input mei value typed ho sake,jaise jaise value change ho vese-vese note me set ho jaye
      };

      const goToLogin = () => {
        history.push("/login")
      }

      const handleSubmit = async(e) => {
        e.preventDefault();
        const response = await fetch('https://my-notebook-mohit.herokuapp.com:/api/auth/createuser', {
            method: 'POST', 
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({name:credentials.name, email:credentials.email, password: credentials.password})
          });
          const json = await response.json();
          if(json.success === true){
            //storing the authtoken
            localStorage.setItem('token',json.authToken);
            history.push("/");
            console.log(json);
            props.showAlert("User registered succesfully!","info");
          } 
          else {
            props.showAlert("Invalid Credentials","danger");
          }
    }

    return (
      <motion.div className="container" id="manku" animate={{scale:[0.5,1]}} transition={{times:[0.1,0.4], ease:'easeInOut'}}>
      <div id="picturebody">
        <img src={imgpath} alt="note-pic" width="100%" />
      </div>
        <div id="loginbody">
        <div className="mt-3">
            <h2 className="my-2">Create your account here </h2>
            <form onSubmit={handleSubmit} className="login-form">
                ..
                ..
                ..
            </form>
            <div className="text-center my-3" id="bottom-text">
            mynotebook
        </div>
        </div>
        </div>
        </motion.div>
    )
}

export default Signup

I am also sharing the HEROKU LOGS here also
Screenshot
hlogs

In written form:

2022-01-22T10:35:31.575900+00:00 app[web.1]: > [email protected] start
2022-01-22T10:35:31.575901+00:00 app[web.1]: > node index.js
2022-01-22T10:35:31.575901+00:00 app[web.1]: 
2022-01-22T10:35:32.186481+00:00 heroku[web.1]: State changed from starting to up
2022-01-22T10:35:32.002450+00:00 app[web.1]: my-notebook backend listening at https://my-notebook-mohit.herokuapp.com:23186
2022-01-22T10:36:01.901941+00:00 app[web.1]: Connected to Mongo Successfully!
2022-01-22T10:37:28.170226+00:00 heroku[router]: at=info method=OPTIONS path="/api/auth/createuser" host=my-notebook-mohit.herokuapp.com request_id=ca6d3e38-ca85-4b8d-834c-2503743f261e fwd="157.34.191.86" dyno=web.1 connect=0ms service=5ms status=204 bytes=301 protocol=https
2022-01-22T10:37:29.785982+00:00 app[web.1]: Cannot read properties of undefined (reading 'findOne')
2022-01-22T10:37:29.788991+00:00 heroku[router]: at=info method=POST path="/api/auth/createuser" host=my-notebook-mohit.herokuapp.com request_id=3f713497-80fb-45e1-a73c-c25fa7f03c4e fwd="157.34.191.86" dyno=web.1 connect=0ms service=25ms status=500 bytes=272 protocol=https
2022-01-22T10:54:57.762199+00:00 heroku[router]: at=info method=GET path="/api/auth/createuser" host=my-notebook-mohit.herokuapp.com request_id=ae666363-1d9c-4d9e-9104-c542c7d10837 fwd="34.230.34.4" dyno=web.1 connect=0ms service=2ms status=404 bytes=434 protocol=https
2022-01-22T10:55:04.937835+00:00 heroku[router]: at=info method=HEAD path="/" host=my-notebook-mohit.herokuapp.com request_id=f132be41-83f5-4a16-9b9d-ed98dda893bf fwd="217.182.175.162" dyno=web.1 connect=0ms service=2ms status=404 bytes=276 protocol=https

Image bounces while rotating – Javascript

I have a project where a robot controls a go-kart.
The robot gives me X and Y coordinates and I displayed them in Chart.js accordingly.
Now I’m trying to display this visuality on a steering wheel so that wherever the go-kart moves, so does the steering wheel.
We also managed to calculate the angular distance of the points, but the steering wheel bounces back together.
For example, if you turn 90 degrees to the left immediately after going 90 degrees, the image will bounce.
Can anyone help me with this?

here is an example problem showing:
enter image description here

function rotate(deg) {
    document.querySelector('#steering_wheel').style.transform = 'rotate('+deg+'deg)';
}


let arrX = [];
let arrY = [];

tag5617.subscribe(function(message) {

    //let X = document.getElementById('posX');

    //X.innerHTML = message.x.toFixed(2);

    //let Y = document.getElementById('posY');

    //Y.innerHTML = message.y.toFixed(2);
   
    myChart.data.datasets[0].data.push({x:message.x.toFixed(2), y:message.y.toFixed(2)});

    arrX.push(message.x);

    arrY.push(message.y);

    let deg = Math.atan2(message.x - arrX[arrX.length-2], message.y - arrY[arrY.length-2]) * 180 / Math.PI;
    rotate(deg)

    myChart.update();

});

Horizontal Pan for D3 Bar Chart

https://plnkr.co/edit/DZqqftUlnjHDbCsH?open=lib%2Fscript.js&preview

This is my Bar Chart and I want it to have Horizontal Panning. But I am unable to incorporate it. Can someone help me with this?

csv data

month,revenue,profit
January,123432,80342
February,19342,10342
March,17443,15423
April,26342,18432
May,34213,29434
June,50321,45343
July,54273,80002
August,60000,30344
September,44432,32444
October,21332,9974
November,79105,48711
December,45246,21785

making an edit button in javascript

I have an Add, Edit and Delete button. The add and delete button is working fine on me but while i’m trying to make an edit button in javascript its not working at all on me. I was trying to search for some solution in this forum but haven’t meet the solution yet.

can anyone help me with the edit button? thanks in advance

//Request Add
$(function() {
    $("#requestAdd").click(function() {
        //Set Field Value
        var dealerName = $("#dealerName :selected").text()
        var amountDeposit = $("#amountDeposit")[0].value;
        var remarks = $("#remarks")[0].value;

        //Data Validation
        if (dealerName == "" || amountDeposit == "" || remarks == "") {
            $("<div></div>").imuiMessageDialog({
                iconType: 'error',
                title: 'Request Data Error',
                buttons: [
                    {
                    'text': 'Close',
                    'click': function() {$(this).imuiMessageDialog('close'); }
                    }
                ]
            }).append('All mandatory fields must be filled before requirement is saved.');
            exit;
        } 
        //Dealer Name Validation
        var dataval = $("#requirementGrid").getGridParam("data");
        for (i in dataval) {
            if (dealerName == dataval[i].dealerName) {
                $("<div></div>").imuiMessageDialog({
                    iconType: 'error',
                    title: 'Request Data Error',
                    buttons: [
                        {
                        'text': 'Close',
                        'click': function() {$(this).imuiMessageDialog('close'); }
                        }
                    ]
                }).append('Priority must be unique in Requirement Detail');
                exit;               
            }       
        }
        //Create Grid Data
        var dataval = $("#requirementGrid").getGridParam("data");
        var newdata = {
            dealerName: dealerName,
            amountDeposit: amountDeposit,
            remarks: remarks,
            status: ""
        };
        dataval.unshift(newdata);
                
        //Set & Reload Grid
        $("#requirementGrid").clearGridData();
        for (i in dataval) {
            var rowNum = parseInt(i) + 1;
            $("#requirementGrid").addRowData(rowNum,dataval[i]);
        }
        $("#requirementGrid").setGridParam({"rowNum":$("#requirementGrid").getRowData().length});
    });
});

//Request Delete
$(function() {
    $("#requestDelete").click(function() {
        var selrow = $("#requirementGrid").getGridParam("selrow");  
        if (selrow != null){
            $("#requirementGrid").delRowData(selrow);
            $("#requirementGrid").setGridParam({"rowNum":$("#requirementGrid").getRowData().length});
        }
        clearFieldValues();
    });
});

//Request Edit
$("#requestEdit").click(requestEdit);

    function requestEdit(){

        var row = $(this).parents("tr");
        var cols = row.children("td");

        activeId = $($(cols[2]).children("button")[0]).data("id");

        $("#dealerName").val($(cols[0]).text());
        $("#amountDeposit").val($(cols[1]).text());
        $("#remarks").val($(cols[2]).text());

        $("#requestAdd").prop("disabled" , true);


    }
    

Why the code returning an array with a single letter instead of whole name?

Learning Destructuring assignment in Javascript and when trying to have an array in object destructuring, just first letter return to console, why it’s happening?

function splitter(name) {
  const [fName, lName] = name.split(" ");
  return { fName, lName };
}

const {fName: [firstWord],lName} = splitter("John Doe");

console.log(splitter("John Doe"));
console.log({fName: [firstWord],lName});

console.log(firstWord);
console.log(lName);

enter image description here

Encountered a time string Unexpected token ‘{‘ error during JavaScript run in console

I’m facing a javascript error Unexpected token ‘{‘ on line 903 . I try to build an open source time zone comparison table and the function I try to add is a list of different time zones that can be selected and should be added to the table. The function does not change the time and I’ve tried to change the javascript function but none of them are working for me. This should be the related code.

<script>
  var d = new Date();

  function {
    var time, date = document.getElementById('hour0,date0');
    var country1 = document.getElementById('country1');
    var country2 = document.getElementById('country2');

    .innerHTML = dat0;

    if (time, date.value == "Afghanistan") {
      document.getElementById("hour0").innerHTML = d.toLocaleTimeString("en-US", {
        timeZone: 'UTC',
        hour: "numeric",
        minute: "2-digit"
      });
      var dat0 = d.toLocaleString('en-us', {
          timeZone: 'UTC',
          weekday: 'short'
        }) +
        "<br>" + d.toLocaleString('en-us', {
          timeZone: 'UTC',
          day: 'numeric',
          month: 'short'
        });
      document.getElementById("date0").innerHTML = dat0;


    }
  }

</script>

The whole code can be found at https://gitlab.com/hmmtime/hmmtime/-/blob/dev/index.html and visible in a browser by https://hmmtime.gitlab.io/hmmtime/

Doesn’t work when changing My working script to Dockable script

Hi i have a working script for after effects,But when i change it to Dockable script,it wont work. Please help me to figure out why? If i take it out of the dock script it is working. i copied this dockable code from goodboy.ninja website.

Here is the code:

(
    function(thisObj) {

buildUI(thisObj);

‍

function buildUI(thisObj) {

var windowName = "Diffrence Checker";

  var myPanel = (thisObj instanceof Panel) ? thisObj : new Window("window", windowName, undefined, {
          resizeable: true
     });

// Dropdown list

var groupOne = myPanel.add("group",undefined,"groupOne");
groupOne.orientation = "row";
groupOne.add("StaticText",undefined,"Main Comp");
var mainDD = groupOne.add("dropdownlist",undefined,compArrayNames);
mainDD.size = [175,25];

var groupTwo = myPanel.add("group",undefined,"groupTwo");
groupTwo.orientation = "row";
groupTwo.add("StaticText",undefined,"Diff File");
var diffDD = groupTwo.add("dropdownlist",undefined,VideoArrayNames);
diffDD.size = [175,25];

// Button code

var createBT = myPanel.add("group",undefined,"createBT");
createBT.orientation = "column";
var mainbutton = createBT.add("button",undefined,"Create");


//myPanel.center();
//myPanel.show();
‍
     myPanel.onResizing = myPanel.onResize = function() {
        this.layout.resize();
     };
     if (myPanel instanceof Window) {
        myPanel.center();
        myPanel.show();
     } else {
        myPanel.layout.layout(true);
        myPanel.layout.resize();
     }

}

// Write your helper functions here
var compArray = [];
var compArrayNames = [];
var VideoArray = [];
var VideoArrayNames = [];

for (var i = 1; i <= app.project.numItems; i++){
    if (app.project.item(i).hasVideo == true && app.project.item(i).file == null) {
        compArray.push (app.project.item(i));
        compArrayNames.push (app.project.item(i).name);
        }
    if (app.project.item(i).hasVideo == true && app.project.item(i).hasAudio== true) {
        VideoArray.push (app.project.item(i));
        VideoArrayNames.push (app.project.item(i).name);
        }
    }

function createCP() {
       app.beginUndoGroup("Editing");
        var comlayer = compArray[mainDD.selection.index];
        var vidlayer = VideoArray[diffDD.selection.index];
        var getcomp = app.project.items.addComp(VideoArrayNames[diffDD.selection.index]+"_DIFF".toString(),1920,1080,1,comlayer.duration,30);
        getcomp.openInViewer();
        addVideofile(comlayer,getcomp);
        addvideotwofile(vidlayer);
        renderQ();
        app.endUndoGroup();
    }

function addVideofile(comlayer) {
    app.project.activeItem.layers.add(comlayer);
    
     
    
    }
function addvideotwofile(vidlayer){
   var newlayer = app.project.activeItem.layers.add(vidlayer);
     newlayer.blendingMode = BlendingMode.DIFFERENCE;
    
    }
function renderQ(){
    
     var Qcomp =app.project.activeItem;
     var Qitem = app.project.renderQueue.items.add(Qcomp);
     }
}
)
(this);

This the final Dockable Code.where is the mistake? please help as i am new to the scripting world.

Faster way than .csv to upload data into Django app

Right now I copy a whole table from a website, paste it into a cell on an excel spreadsheet and it formats it into a .csv file.

After the .csv is made I upload the file into my database via a Django app.

I also have a model form if I wanted to enter the data manually.

What I was wondering is if there is a way to skip a step to make the process faster. Maybe copy the table from the web and paste it into a form cell and it gets formatted like excel does.

Any tips or ideas are greatly appreciated.

My image is not loading on the page while launching the page through localhost

Below is my Pug code.

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
     style 
        include FrontPageStyle.css
</head>
<section id="rotate">
<nav>
    <ul id="TopBar">
        <li><a href="/Home">Home</a></li>
        <li><a href="/About">About</a></li>
        <li><a href="/Contact">Write me</a></li>
    </ul>
</nav>
<section id="h">
    <ul id="Name_Section">
        <div id="Hey">
            <li id="Iam">Hey, I'm</li>
            <li style="padding-top: 25px;">PRAVEEN KUMAR </li>
        </div>
        <li id="square"></li>
    </ul>
</section>
</section>
<section>
    <ul class="MySkill1">
        <li class="line1"></li>
        <li >My Skills</li>
        <li class="line2"></li>
    </ul>
</section>
<section id="Skill_Section1">
    <ul class="Cards">
        <li id="list1">This is list1</li>
        <li id="list2">This is list2</li>
        <li id="list3">This is list3</li>
        <li id="list4">This is list4</li>
    </ul>
</section>
<section>
    <ul class="MySkill2">
        <li class="line1"></li>
        <li>I Build Beautiful</li>
        <li class="line3"></li>
    </ul>
</section>
<section id="Skill_Section2">
    <div class="Button">
        <li><button class="Next_Button" onclick="nextimage()"> &laquo;</button></li>
        <li><button class="Next_Button">&raquo;</button></li>
    </div>
</section>
<section id="Mythought">
<div class="MySkill3">
  <li class="line1"></li>
  <li style="font-weight: bold;">My Thoughts</li>
  <li class="line4"></li>
</div>
    <ul class="Cards">
      <li id="list1">This is 2list 1</li>
      <li id="list2">This is 2list2</li>
      <li id="list3">This is 3list3</li>
      <li id="list4">This is 3list4</li>
    </ul>
</section>

Here below is my CSS code.

#square{
   width: 250px;
   height: 250px;
    background-image: url('../ff.png');
    background-repeat: no-repeat;
    background-size: 250px 250px;
}

And Below is the nodejs code in the javascript file.

const express=require('express');
const { redirect } = require('express/lib/response');
const { link, readdir } = require('fs');
const app=express();
app.use('/static',express.static('static'));
const path=require('path');
app.set('view engine','pug');
app.set('Views',path.join(__dirname,'Views'));
app.get('/Home',(req,res)=>{
    res.send("This is Home Page");
});
const port=80;
app.get('/FrontPage', (req, res)=>{
    res.status(200).render('FrontPage', { title: 'Hey Praveen', message: 'Hello there!, thanks for your code' })
  });
app.get('/About', (req, res)=>{
    res.status(200).render('AboutPage', { title: 'Hey Praveen', message: 'Hello there!, thanks for your code' })
  });
app.get('/Contact', (req, res)=>{
    res.status(200).render('ContactPage', { title: 'Hey Praveen', message: 'Hello there!, thanks for your code' })
  });
  app.listen(port,()=>{
   console.log("This application started successfully on port ");
});

These are the code that I wrote and launched my site through this, everything works well but the images that I use don’t appear there. Instead of offline images if I use an online image URL then it works well but not with the images that are in my folder. I had given the path correctly as if I launch it through live server extension then the images also loads properly but not with localhost server.

How can I extend an abstract EventEmitter class, with some default events?

Could anyone help with this please?

How can I extend an abstract EventEmitter class, with common events? (I’m using https://github.com/andywer/typed-emitter)

Example:

import EventEmitter from "events";
import TypedEmitter from "typed-emitter";

type BaseEvents = {
  BASE_EVENT: (arg: string) => void;
};

abstract class BaseEmitter<T> extends (EventEmitter as {
  new <T>(): TypedEmitter<T>;
})<T> {
  constructor() {
    super();
    // How can I make this type safe ????
    this.emit("BASE_EVENT", "string-value"); // <-- How can I achieve type safety here
  }
}

type ImpOneEvents = {
  C1_EVENT: (a: number) => void;
};
class ImpOne extends BaseEmitter<ImpOneEvents> {
  constructor() {
    super();
    this.emit("C1_EVENT", 1); // OK: type checks ok (GOOD)
    this.emit("C1_EVENT", "bla"); // ERROR: string not assignable (GOOD)
  }
}

type ImpTwoEvents = {
  C2_EVENT: (a: boolean) => void;
};
class ImpTwo extends BaseEmitter<ImpTwoEvents> {
  constructor() {
    super();
    this.emit("C2_EVENT", true); // OK: type checks ok (GOOD)
  }
}

const impTwo = new ImpTwo();
impTwo.on("C2_EVENT", (a) => {
  parseFloat(a); // ERROR: Type of boolean not assignable to parameter of type string (GOOD)
});

I’ve tried

type BaseEvents = {
  BASE_EVENT: (arg: string) => void;
};

abstract class BaseEmitter<T = {}> extends (EventEmitter as {
  new <T>(): TypedEmitter<T>;
})<T & BaseEvents> {
...

And lots of other things. The above results in

Argument of type '[string]' is not assignable to parameter of type 'Arguments<(T & BaseEvents)["BASE_EVENT"]>'.

For line

this.emit("BASE_EVENT", "string-value"); // <-- How can I achieve type safety here

How to count occurrence of unique keys from multiple objects in Javascript?

There are multiple objects that I extracted from multiple json files. Through iteration, I then transformed each json file into an object that contains unique key value pairs. The goal is to make a new object that has count occurrence of each unique key among all objects. My issue is it keeps counting each object multiple times (the total numbers of the objects) instead of just once.

pseudo code as below:

//method of counting occurrence of unique keys

const totalCounts = (obj) => {
  let sum = 0;
  let result = {};
  for (let el in obj) {
    if (obj.hasOwnProperty(el)) {
      sum += parseFloat(obj[el]);
      result[el] = sum;
    }
  }
  return result;
};

//extract json files then transform each file into an array of objects
    files.forEach(fileName, i){
        const arrayOfObj = json.keyName;
        let occurrence = arrayOfObj.reduce(
            (acc, o) => ((acc[o.uniqueKey] = (acc[o.uniqueKey] || 0) + 1), acc),
            {},
          );
      //count occurrences of all unique keys among all the arrays of objects

const output = totalCounts(occurrence);
//some logic to pass the output variable to make a new object that has the total occurrence for all objects.
    }

My issue I think is a scope problem essentially that I’m struggling with. I know the occurrence variable is what I need to use for the end result and it caused duplicated iterations because the logic lives inside of the loop instead of outside. Could anyone give me some pointers about how to debug this problem?

What I want is an output like:

{key1: 3, key2: 5, ....}

What I got so far is:

{key1: 33, key2:25 ...}, { key1: 12, key2: 3...}, ....30 more objects

Trying to pull dates from HTML elements with JavaScript and compare them to today’s date and if they are within 30 days change the text color

I am completely new to programming/web development.

What I am trying to do:
I am trying to write JavaScript that will take the date from a webpage or an online spreadsheet and change the color of the text or cell background. The color change will be based on if the date taken from the HTML element or online spreadsheet is within 14 or 30 days from today’s date.

Here is a sample of html elements I would like to work on. I put the dates in various formats to try and work with them.

The Javascript I have written so far I am posting here because I can get the elements to change color but I don’t think the change is actually based on the number of days and I am not able to compare a the number of days I want.

const now = new Date().toDateString();
const date1 = document.getElementById('test1').innerText;

for (let i = 0; i <= test.length; i++) {

  i += test[i];

  if (date1 <= now)
    console.log('safe');
  if (date1 >= now)
    document.getElementsByClassName('test')[0].style.color = 'purple';
};
<div class='test'>
  <p id="test1">February 22 2022</p>
  <br>
  <p id="test">17/2/2022</p>
  <br>
  <p id="test">17 3 2022</p>
  <br>
  <p id="test">17 4 2022</p>
  <br>
</div>