Can’t change button color using JavaScript. Error: Uncaught TypeError: Cannot set properties of undefined (setting ‘backgroundColor’)

I am a beginner in JS so can’t resolve. Please help.
I can’t change the button background color.

Here’s the code ->

<!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">`enter code here`
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>JS Game</title>
    
        <link rel="stylesheet" href="style.css">
    
    </head>
    
    <body>
        <button class="btn1" onclick="change()"></button>
    </body>
    
    <script>
        function change() {
            document.getElementsByClassName('btn1').style.
            backgroundColor="lightblue";
        }
    </script>
    
    </html>

RegEx length matching going wrong?

Regular Expressions are not quite my forte and I am having some trouble understanding just why the following is happening

function showMatch(id)
{
 const spn = document.getElementById(id);
 const value = document.getElementById(`${id}Test`).innerText;
 
 let result = /^[a-zA-Z{1}[a-zA-Z0-9_s&]{2,17}$/.test(value);
 
 spn.innerHTML = result;
}

showMatch('one');
showMatch('two');
showMatch('three');
showMatch('four');
div > span:last-of-type
{
 padding-left:2rem;
 font-weight:bold;
} 
<div><span id='oneTest'>S</span><span id='one'></span></div>
<div><span id='twoTest'>St</span><span id='two'></span></div>
<div><span id='threeTest'>Sta</span><span id='three'></span></div>
<div><span id='fourTest'>Stac</span><span id='four'></span></div>

The regex I am using here is /^[a-zA-Z{1}[a-zA-Z0-9_s&]+$/ with the intent being as follows

  • Require the first character to be alphabetic
  • Require the subsequent characters to be alphanumeric or a space or an ampersand
  • Require the total length to be between 3 and 18 characters

I have been assuming that [a-zA-Z]{1} would consume the first character which is why the second part tests for a length of between 2 and 17 characters. Clearly, that is not how it is working or else my second test value St would not yield TRUE. How can this be corrected?

UnhandledPromiseRejectionWarning when deploying Twilio Video server

I am following Twilio’s documentation for starting a live video application.

I set up the application but when I try to deploy it with npm run serverless:deploy:

it returns this error:

(node:1198) UnhandledPromiseRejectionWarning: Error: Authenticate
    at ServicePage.Page.processResponse (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/twilio/lib/base/Page.js:156:11)
    at ServicePage.Page (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/twilio/lib/base/Page.js:16:22)
    at new ServicePage (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/twilio/lib/rest/serverless/v1/service.js:417:30)
    at Function.<anonymous> (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/twilio/lib/rest/serverless/v1/service.js:251:24)
    at Promise_then_fulfilled (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/q/q.js:766:44)
    at Promise_done_fulfilled (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/q/q.js:835:31)
    at Fulfilled_dispatch [as dispatch] (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/q/q.js:1229:9)
    at Pending_become_eachMessage_task (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/q/q.js:1369:30)
    at RawTask.call (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/asap/asap.js:40:19)
    at flush (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/asap/raw.js:50:29)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1198) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1198) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I believe this snippet in Twilio’s code is causing the problem:

/**
 * Creates a new promise, waits for this promise to be resolved, and informs
 * either the fullfilled or rejected handler of the result. Whatever result
 * comes of the fulfilled or rejected handler, a value returned, a promise
 * returned, or an error thrown, becomes the resolution for the promise
 * returned by `then`.
 *
 * @param fulfilled
 * @param rejected
 * @returns {Promise} for the result of `fulfilled` or `rejected`.
 */
Promise.prototype.then = function Promise_then(fulfilled, rejected, ms) {
    var self = this;
    var deferred = defer();

    var _fulfilled;
    if (typeof fulfilled === "function") {
        _fulfilled = function Promise_then_fulfilled(value) {
            try {
                deferred.resolve(fulfilled.call(void 0, value));
            } catch (error) {
                deferred.reject(error);
            }
        };
    } else {
        _fulfilled = deferred.resolve;
    }

    var _rejected;
    if (typeof rejected === "function") {
        _rejected = function Promise_then_rejected(error) {
            try {
                deferred.resolve(rejected.call(void 0, error));
            } catch (newError) {
                deferred.reject(newError);
            }
        };
    } else {
        _rejected = deferred.reject;
    }

    this.done(_fulfilled, _rejected);

    if (ms !== void 0) {
        var updateEstimate = function Promise_then_updateEstimate() {
            deferred.setEstimate(self.getEstimate() + ms);
        };
        this.observeEstimate(updateEstimate);
        updateEstimate();
    }

    return deferred.promise;
};

Should I edit this code directly and if so how could I fix the unhandled promise?

Is css and html files necessary?

Given javascript can manipulate with the DOM tree and do all sort of things, I wonder why dont we just use one javascript instead to replace html and css files? Is that possible?

If that is possible, why are we still sticking to use html and css files still? Is it because historical reason?

Express GET request not reloading page

I’m trying to send the client the next HTML page (create.html) as a response to a GET request (fired by button) using fetch. I am purposely trying to avoid using a form due to formatting issues and potential future scaling issues. The code registers that the request is sent, received, and is responded to with the file but it simply does not reload the page with it. *res.redirect does also not work. I’ve attached my code bellow.
JavaScript:

app.get('/', function(req, res) {
    console.log(`[00]: Get request recieved at '/'`);
    res.sendFile('public/start.html' , { root : __dirname});
})

app.get('/login', function(req, res) {
    console.log(`[01]: Get request recieved at '/login'`);
    res.sendFile('public/login.html' , { root : __dirname});
})
app.get('/create', function(req, res) {
    console.log(`[02]: Get request recieved at '/create'`);
    res.sendFile('public/create.html' , { root : __dirname});
})

HTML:

<html>
    <head>
        <meta charset="utf-8">
        <title>HOME PAGE</title>
    </head>
    <body>
        <h1 id='title'>Welcome User!</h1>
        <h2>Select an option bellow!</h2>
        
        <button id="btnToLogin">Login</button>
        <button id="btnToCreate">Create Account</button>

        <p>-ADMIN PANEL-</p>
        <button id="btnDisplay">Display Database</button>
        <button id="btnTruncate">Truncate Database</button>
        <p id='displayText' >[displayText]: Nothing seems to be here...</p>
        
        <script src="start.js"></script> 
    </body>

</html>

HTML JavaScript:

// Gets elements from start.html
var btnToLogin = document.getElementById('btnToLogin');
var btnToCreate = document.getElementById('btnToCreate');
var btnDisplay = document.getElementById('btnDisplay');
var btnTruncate = document.getElementById('btnTruncate');
var displayText = document.getElementById('displayText');

btnToLogin.addEventListener('click', function() { fetch('/login', { method: 'GET' }) });
btnToCreate.addEventListener('click', function() { fetch('/create', { method: 'GET'}) });

I’ve cut out most of my code, just unnecessary for the problem I believe. Everything is required properly and server is set up. And incase it matters i’ve attached a picture of the file structure. Thanks.
File Structure

How to improve my add class to element functions

I want to write a vanilla js function that have the same function as in jQuery addClass() function. I have wrote these code below.

function checkType(value){ //get type of target
    var name = "";
    var type = value.split("");
    for(var i=1; i<type.length; i++){
        name = name + type[i];
    }
    if(type[0] == "#"){ //if id
        return document.getElementById(name);   //return id
    }else if(type[0] == "."){ //if class
        return document.getElementsByClassName(name); //return class
    }else{
        return null;
    }
}

function classesToArray(value){ 
    if(value != null){
        value = value.split(" ");
        return value;
    }
    return [];
}

function addClass(target, value) {
    var element = checkType(target);
    var classes = classesToArray(value);
    if(element != null){
        classes.forEach(function(classItem){
            if(element.length){
                for(var i = 0; i < element.length; i++){
                    element[i].className += " " + classItem;
                }
            }else{
                element.className += " " + classItem;
            }
        });
    }
}

So the way to use it is as below

addClass('.elementIdName','nameOfClassToAdd');    //target Id if begin with .
addClass('#elementClassName','nameOfClassToAdd'); //target className if begin with #

addClass('.elementIdName', 'nameOfClass1 nameOfClass2'); //you can also add multiple class names

The code works. But I know there’s a lot of room to improve it. I’d really appreciate if someone can show me the ropes on what should i look for to improve this. Thanks

Modal not getting opened on clicking the image of gallery component

I’m trying to open a model when I click on the image component in gallery. Here I’m not getting the “flagImage” variable updated in onPress method of TouchableOpacity or the modal component is not getting the updated value of “flagImage” when onPress of TouchableOpacity changes its value. I need help here. The modal doesn’t open at all whenever I touch the image component. It just does nothing 🙁 Below is the code for gallery.component.js:

import React from 'react';
import { View, Image, ScrollView, TouchableOpacity, Modal, Text } from 'react-native';
import styles from './cameraStyles';

export default ({captures=[], flagImage=true}) => (
    <ScrollView 
        horizontal={true}
        style={[styles.bottomToolbar, styles.galleryContainer]} 
    >
        {captures.map(({ uri }) => (
            <View style={styles.galleryImageContainer} key={uri}>
                <TouchableOpacity 
                    onPress={()=> {
                        flagImage = !flagImage;
                        console.log('Touch: "'+flagImage+'"');          
                    }}
                >
                    <Image source={{ uri }} style={styles.galleryImage}/>
                </TouchableOpacity>
                <Modal visible={flagImage} onPress={() => {console.log('Modal: "'+flagImage+'"');flagImage = !flagImage;}} onRequestClose={() => flagImage = ! flagImage}>
                      <View>
                            <Image source={{ uri }} style={styles.galleryImageLarge}/> 
                      </View>
                </Modal>
            </View>
        ))}
    </ScrollView>
);    

How to get VSCode to recognize BabylonJS for code-completion and hints?

I suspect it is because I am using plain Javascript, but the BabylonJS CDN is Typescript.

I have tried with the CDN in my HTML and also by wgetting/storing the babylon.js minified version locally.

Both work just fine and I can load my project in the browser.

But I cannot seem to get VSCode to recognize the BABYLON instance. It also doesn’t suggest methods as I type etc.

Is there a way to get VSCode to recognize BabylonJS?

enter image description here

JS question “i dont know why i am getting a different answer”

let a = 10;

let b = “20”;

let c = 80;

console.log(–c + +b + –a * +b++ – +b * a + –a – +true);

**I think I should get 108 then multiple it by -1 then multiple it by 16 which should result in -1728 however I am getting an answer of 97!!!!

how is that possible?

when I broke the problem into 3 pieces (–c + +b + –a)(+b++ – +b)(a + –a – +true) the computer agreed with me that the first part should be 108 then -1.

I need help guys. someone explain it to me, please.

THANKS**

JavaScript Two Sum Debugging (n time complexity)

I am trying to achieve n-time-complexity for a two sum function via utilization of hashes in JavaScript. I’ve come up with the code below, but for some reason it does not capture all of the paired indices. The function is supposed to return pairs of indices of integers in an array that add up to zero.

Array.prototype.twoSumHash = function () {
    let newArr = [];
    const hash = {};
    this.forEach((ele, idx) => {
        if (hash[ele * -1]) {
            const pair = [hash[ele * -1], idx];
            newArr.push(pair);
        }
        hash[ele] ? hash[ele].push(idx) : hash[ele] = idx;
    });
    return newArr;
};

console.log([1, -1, 2, 3, 4, -2].twoSumHash());

This function only seems to return the 2 and -2 ([2,5]), but not the 1 and -1 ([0, 1]). Please help, and thank you!

Visual Studio Code built in JavaScript IntelliSense not working

Visual studio code built in JavaScript IntelliSense, debugging, formatting not working.
I’ve tried many solutions but didn’t work. I also reinstalled VS Code but it didn’t fix the issue. Guide me how to fix this problem.

setting.json file code

{
  "workbench.startupEditor": "newUntitledFile",
  "editor.wordWrap": "on",
  "php.executablePath": "C:/xampp/php/php.exe",
  "php.validate.executablePath": "C:/xampp/php/php.exe",
  "workbench.editor.untitled.hint": "hidden",
  "security.workspace.trust.untrustedFiles": "open",
  "editor.linkedEditing": true,
  "liveServer.settings.donotShowInfoMsg": true,
  "workbench.iconTheme": "material-icon-theme",
  "editor.minimap.enabled": false,
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "window.restoreFullscreen": true,
  "files.exclude": {
    "**/.git": false
  },
  "emmet.triggerExpansionOnTab": true,
  "emmet.includeLanguages": {
    "vue-html": "html",
    "vue": "html",
    "javascript": "javascriptreact"
  },
  "zenMode.centerLayout": false,
  "liveSassCompile.settings.generateMap": false,
  "liveSassCompile.settings.formats": [
    {
      "format": "nested",
      "extensionName": ".css",
      "savePath": "/css"
    }
  ],
  "json.maxItemsComputed": 25000,
  "liveServer.settings.donotVerifyTags": true,
  "workbench.colorTheme": "Winter is Coming (Dark Blue - No Italics)",
  "bracket-pair-colorizer-2.depreciation-notice": false,
  "emmet.showSuggestionsAsSnippets": true,
  "editor.suggestSelection": "first",
  "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue"
}

How to generate a lines inside of vue-accordion on each checkbox click in Vuejs?

data: function () {
    return {
      show: false,
    };
  },
  methods: {
    toggleItem: function () {
      this.show = !this.show;
    },
  },
  <div class="wrapper">
    <div class="accordion">
      <input type="checkbox" @click="toggleItem" />

      <h2 class="title">
        <slot name="title"></slot>
      </h2>
    </div>
    <div v-show="show" class="content">
      <slot name="content"></slot>
    </div>
  </div>

I want to generate a lines like below, inside of the vue-accordion. every time. When ever user click on each checkbox separately.

So to achieve like above, do i need any other plugins or with css can i achieve that.

Working code snippet:- https://codesandbox.io/s/vue-accordion-component-forked-vwpi8?file=/src/components/Accordion.vue

generate lines like this