console returns output for querySelectorAll as null even when Node exists

I am trying to use javascript to find element containing a class among bunch of elements and assign its index no to a variable, but the output of following code is always null, even when the document contains element with the class. Alert windows shows 25.

elementzParent = document.querySelectorAll(".question-counter i");
alert(elementzParent.length);
console.log(elementzParent);
for (let i = 0; i < elementzParent.length; i++) {
  elementzclass = elementzParent[i].classList;
  console.log(elementzclass);
  if (elementzclass.contains('fa-lg')) {

    var PYQNo = i + 1;
    console.log(PYQNo);
  };
};

If I change the console.log to console.info

elementzParent = document.querySelectorAll(".question-counter i");
alert(elementzParent.length);
console.info(elementzParent);
for (let i = 0; i < elementzParent.length; i++) {
  elementzclass = elementzParent[i].classList;
  console.info(elementzclass);
  if (elementzclass.contains('fa-lg')) {

    var PYQNo = i + 1;
    console.log(PYQNo);
  };
};

the output becomes 25 in alert window and

NodeList(25) [ i.fa.fa-circle.ng-tns-c105-1.fa-lg.correct, i.fa.fa-circle.ng-tns-c105-1, i.fa.fa-circle.ng-tns-c105-1, i.fa.fa-circle.ng-tns-c105-1, i.fa.fa-circle.ng-tns-c105-1, i.fa.fa-circle.ng-tns-c105-1, i.fa.fa-circle.ng-tns-c105-1, i.fa.fa-circle.ng-tns-c105-1, i.fa.fa-circle.ng-tns-c105-1, i.fa.fa-circle.ng-tns-c105-1, … ]
DOMTokenList(5) [ "fa", "fa-circle", "ng-tns-c105-1", "fa-lg", "correct" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
DOMTokenList(3) [ "fa", "fa-circle", "ng-tns-c105-1" ]
undefined

HTML is

   <div _ngcontent-oly-c105="" class="question-counter ng-tns-c105-1">   
      <span _ngcontent-oly-c105="" class="ng-tns-c105-1 ng-star-inserted" style="">
        <span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1 fa-lg correct"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><span _ngcontent-oly-c105="" class="question-progress-bar ng-tns-c105-1 ng-star-inserted">
          <i _ngcontent-oly-c105="" aria-hidden="true" class="fa fa-circle ng-tns-c105-1"></i>
        </span><!---->
      </span><!---->
      <!---->
    </div>

I trying javascript for first time by reading from web and running this in firefox console. I would like some guidance as to why my code may not be working?

I tried to use getAttribute() instead of classlist first but that didn’t work too.
Tried console.info which returns all the matching nodes, but it was of no benefit.
Also tried getElementsByClassName instead of querySelectorAll still null output.
Also tried using window.onload.
Works on codepen.io

Transform array to the following format

I have an array of objects that have 2 fields key and type, the type field is practice or theory

Result:

  1. group the array by key

  2. transform the array: in the new array the object with type practice should come in the even index and object with type theory should be in the odd index. (check the input and the output if my explanation wasn’t clear)

here’s my code but it doesn’t work as expected in the transform the array

function transformArray(arr) {
  const grouped = arr.reduce((result, item) => {
    const key = item.key;
    if (!result[key]) {
      result[key] = { key, values: [] };
    }
    result[key].values.push(item);
    return result;
  }, {});

  for (const group in grouped) {
    const values = grouped[group].values;
    const newValues = [];
    for (let i = 0; i < values.length; i++) {
      const item = values[i];
      if (item.type === 'practice' && i % 2 === 0) {
        newValues.push(item);
      } else if (item.type === 'theory' && i % 2 === 1) {
        newValues.push(item);
      }
    }
    grouped[group].values = newValues;
  }

  return Object.values(grouped);
}

example input:

const input = [
{ key: 'A', type: 'practice' },
{ key: 'A', type: 'practice' },
{ key: 'A', type: 'theory' },
{ key: 'A', type: 'theory' },

{ key: 'B', type: 'practice' },
{ key: 'B', type: 'theory' },
{ key: 'B', type: 'practice' },

{ key: 'C', type: 'practice' },
{ key: 'C', type: 'theory' },
{ key: 'C', type: 'practice' },
]

output

[
  {
    key: 'A',
    values: [
      { key: 'A', type: 'practice'},  // index = even ==> practice
      { key: 'A', type: 'theory' },    // index = odd ==> theory
      { key: 'A', type: 'practice'}, // index = even ==> practice
      { key: 'A', type: 'theory'}, // index = odd ==> theory
    ],
  },
  {
    key: 'B',
    values: [
      { key: 'B', type: 'practice' },
      { key: 'B', type: 'theory',},
      { key: 'B', type: 'practice' },
    ],
  },
  {
    key: 'C',
    values: [
      { key: 'C', type: 'practice' },
      { key: 'C', type: 'theory', },
      { key: 'C', type: 'practice'},
    ],
  },
]

how can i convert the html file to a jsx file?

function calculate() {
  var num1, num2, num3, res;

  num1 = Number(document.getElementById('length').value);
  num2 = Number(document.getElementById('width').value);
  num3 = Number(document.getElementById('height').value);
  res = num1 * num2 * num3;
  document.formcalcvolume.volume.value = (res).toFixed(2);

  document.getElementById("tbl").innerHTML = "";

  if (res > 0) {

    var table = `<tr>
                              <td data-col-title="Name" class="tabledatastyle"><b>${"GEN S"}</b></td>
                              <td data-col-title="CADR (m3/h)">${180}</td>
                              <td data-col-title="Volume">${res.toFixed(2)}</td>
                              <td data-col-title="100% ACH">${(180/res).toFixed(2)}</td>
                              <td data-col-title="50% ACH">${(90/res).toFixed(2)}</td>
                          </tr>`;
    document.getElementById('tbl').innerHTML += table;

    var table = `<tr>
                              <td data-col-title="Name" class="tabledatastyle"><b>${"GEN X"}</b></td>
                              <td data-col-title="CADR (m3/h)">${727}</td>
                              <td data-col-title="Volume">${res.toFixed(2)}</td>
                              <td data-col-title="100% ACH">${(727/res).toFixed(2)}</td>
                              <td data-col-title="50% ACH">${(727/(res*2)).toFixed(2)}</td>
                          </tr>`;
    document.getElementById('tbl').innerHTML += table;

    var table = `<tr>
                              <td data-col-title="Name" class="tabledatastyle"><b>${"GEN Y"}</b></td>
                              <td data-col-title="CADR (m3/h)">${633}</td>
                              <td data-col-title="Volume">${res.toFixed(2)}</td>
                              <td data-col-title="100% ACH">${(633/res).toFixed(2)}</td>
                              <td data-col-title="50% ACH">${(633/(res*2)).toFixed(2)}</td>
                          </tr>`;
    document.getElementById('tbl').innerHTML += table;

    var table = `<tr>
                              <td data-col-title="Name" class="tabledatastyle"><b>${"GEN Z"}</b></td>
                              <td data-col-title="CADR (m3/h)">${1156}</td>
                              <td data-col-title="Volume">${res.toFixed(2)}</td>
                              <td data-col-title="100% ACH">${(1156/res).toFixed(2)}</td>
                              <td data-col-title="50% ACH">${(1156/(res*2)).toFixed(2)}</td>
                          </tr>`;
    document.getElementById('tbl').innerHTML += table;

    clearForm();

  } else reset();
}

function clearForm() {
  document.getElementById('length').value = null;
  document.getElementById('height').value = null;
  document.getElementById('width').value = null;

}

function reset() {
  document.getElementById('length').value = null;
  document.getElementById('height').value = null;
  document.getElementById('width').value = null;
  document.getElementById('volume').value = null;

  document.getElementById("tbl").innerHTML = "";
}

function cleartable() {}
<div class="boddy">

  <div class="total">
    <div class="cadr-info">
      <form name="formcalcvolume" id="form1" class="classicForm">
        <h3 style="color:rgb(64,141,194)">Room Volume</h3>
        <p>
          <label><b>Length (m)</b><b style="color: red">*</b></label>
          <input type="text" id="length" />
        </p>
        <p>
          <label><b>Width (m)</b><b style="color: red">*</b></label>
          <input type="text" id="width" />
        </p>
        <p>
          <label><b>Height (m)</b><b style="color: red">*</b></label>
          <input type="text" id="height" />
        </p>
        <p>
          <button type="button" onclick="calculate()">Calculate</button>
        </p>
        <p>
          <button type="button" onclick="reset()">Reset</button>
        </p>
        <p>
          <label>Room Volume  (m3)</label>
          <input type="text" id="volume" />
        </p>
      </form>
    </div>
    <div class="cadr-info">
      <h3 style="color:rgb(64,141,194)"><b>Air Changes per Hour</b></h3>

      <form class="cadr-form">
        <table id="cadrtable" class="cadr-table" style="width:100%">
          <thead class="tableheading">
            <tr>
              <th scope="col" style="background-color:#6a78ed; color:white;"><b>Name</b></th>
              <th scope="col" style="background-color:#6a78ed; color:white;"><b>CADR(m3/h)</b></th>

              <th scope="col" style="background-color:#6a78ed; color:white;"><b>Room Volume</b></th>
              <th scope="col" style="background-color:#6a78ed; color:white;"><b>100% ACH</b></th>
              <th scope="col" style="background-color:#6a78ed; color:white;"><b>50% ACH</b></th>
            </tr>

          </thead>
          <tbody id="tbl" class="tablecontent"></tbody>
        </table>

      </form>
      <h4 id="emaillink" style="color:rgb(64,141,194)">For a more detailed report, contact us on <br>[email protected]</h4>
    </div>

  </div>
</div>

How would I force react to reconstruct component? [duplicate]

This might be a stupid question but I have some useEffects that act as initial triggers and set up the component.
Now, I could trigger all these useEffects with some flag in the dependancy array and kinda fake a “reconstruction” of the component but is there a way to do it properly?

So that the component rerenders as if its doing it for the first time?
Thanks for any suggestions…

I want a solution to content_security_policy refuse to load facebook sdk codes in chrome extension manifest v3

I am building a chrome extension
And I add the following code to a page within its files

window.fbAsyncInit = function () {
FB.init({
appId: "761023588971600",
autoLogAppEvents: true,
xfbml: true,
version: "v16.0",
});
};
var script = document.createElement("script");
script.async = true;
script.defer = true;
script.crossOrigin = "anonymous";
script.src = "https://connect.facebook.net/en_US/sdk.js";
document.head.appendChild(script);

my manifest.json

{
"manifest_version": 3,
"name": "Ultra Share Bot",
"description": "Share with ease",
"version": "1.0",
"icons": {
"16": "img/share_icon.png",
"32": "img/share_icon.png",
"48": "img/share_icon.png",
"128": "img/share_icon.png"
},
"action": {
"default_popup": "popup.html",
"default_icon": "img/share_icon.png",
"default_title": "Share with ease now"
},
"background": {
"service_worker": "background.js"
},
"permissions": [
"tabs"
]
}

These two errors show me how to solve it

Refused to load the script 'https://connect.facebook.net/en_US/sdk.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
Refused to load the script 'https://connect.facebook.net/en_US/sdk.js' because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules' http://localhost:* http://127.0.0.1:*". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

I tried adding this code to a file manifest.json

"content_security_policy": {
    "extension_pages": "script-src 'self' https://connect.facebook.net; object-src 'self';"
  }

But it didn’t work out
Once the hosting was updated, Chrome blocked it and showed the following error

Error
'content_security_policy.extension_pages': Insecure CSP value "https://connect.facebook.net" in directive 'script-src'.
Could not load manifest.

Cannot read properties of undefined (reading ‘push’) in node js

i’m trying to add roomSchema to a userSchema

this is my code

router.post('/join-room', async (req, res) => {
  const { roomId, userId } = req.body;
  try {
    const user = await User.findById(userId);
    const room = await Room.findById(roomId);
    if (!user || !room) {
      return res.status(404).json({ message: 'User or room not found' });
    }
    user.rooms.push(roomId);
    await user.save();
    res.json({ message: 'User joined room successfully' });
  } catch (error) {
    console.error(error);
  }
});

this is my json


{
  _id: new ObjectId("6436c40c989d571ad31563a8"),
  name: 'jquery',
  email: '[email protected]',
  password: '$2a$10$fdPk3EzPPZc4SDxGmYnj3usFm9IlU0SNb.Ek4hINXHTfNSAclscxW',
  __v: 0
} {
  _id: new ObjectId("6436bf25f70ece2db5576081"),
  created_date: 2023-04-12T14:24:37.439Z,
  name: 'vue',
  __v: 0
}

this my error

 Cannot read properties of undefined (reading 'push')

please how can i go about this

How to add useEffect hook in nextjs with antd

This is my first project in next.js, I am trying to add an existing ProLayout component from the ant design library
I understand that the error I am getting is because my app is being rendered on the server side, right at that moment the dom does not exist, for that reason you don’t get the document because it does not exist.

I understand that.
What I don’t understand is how to implement the useEffect hook inside the component because document is inside the return

Error:

Server Error
ReferenceError: document is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
src/pages/index.tsx (349:14) @ document

  347 | return [
  348 |   props.layout !== "side" &&
> 349 |   document.body.clientWidth > 1400 ? (
      |  ^
  350 |     <SearchInput />
  351 |   ) : undefined,
  352 |   <InfoCircleFilled key="InfoCircleFilled" />,

What I need:

I need to implement useEffect inside Index

Index

import {
  CaretDownFilled,
  DoubleRightOutlined,
  GithubFilled,
  InfoCircleFilled,
  LogoutOutlined,
  PlusCircleFilled,
  QuestionCircleFilled,
  SearchOutlined,
} from "@ant-design/icons";
import type { ProSettings } from "@ant-design/pro-components";
import {
  PageContainer,
  ProCard,
  ProConfigProvider,
  ProLayout,
  SettingDrawer,
} from "@ant-design/pro-components";
import { css } from "@emotion/css";
import {
  Button,
  Divider,
  Input,
  Dropdown,
  Popover,
  theme,
} from "antd";
import React, { useEffect, useState } from "react";
import defaultProps from "./_defaultProps";

const Item: React.FC<{ children: React.ReactNode }> = (props) => {
  const { token } = theme.useToken();
  return (
    <div
      className={css`
        color: ${token.colorTextSecondary};
        font-size: 14px;
        cursor: pointer;
        line-height: 22px;
        margin-bottom: 8px;
        &:hover {
          color: ${token.colorPrimary};
        }
      `}
      style={{
        width: "33.33%",
      }}
    >
      {props.children}
      <DoubleRightOutlined
        style={{
          marginInlineStart: 4,
        }}
      />
    </div>
  );
};

const List: React.FC<{
  title: string;
  style?: React.CSSProperties;
}> = (props) => {
  const { token } = theme.useToken();

  return (
    <div
      style={{
        width: "100%",
        ...props.style,
      }}
    >
      <div
        style={{
          fontSize: 16,
          color: token.colorTextHeading,
          lineHeight: "24px",
          fontWeight: 500,
          marginBlockEnd: 16,
        }}
      >
        {props.title}
      </div>
      <div
        style={{
          display: "flex",
          flexWrap: "wrap",
        }}
      >
        {new Array(6).fill(1).map((_, index) => {
          return <Item key={index}>具体的解决方案-{index}</Item>;
        })}
      </div>
    </div>
  );
};

const MenuCard = () => {
  const { token } = theme.useToken();
  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
      }}
    >
      <Divider
        style={{
          height: "1.5em",
        }}
        type="vertical"
      />
      <Popover
        placement="bottom"
        overlayStyle={{
          width: "calc(100vw - 24px)",
          padding: "24px",
          paddingTop: 8,
          height: "307px",
          borderRadius: "0 0 6px 6px",
        }}
        content={
          <div style={{ display: "flex", padding: "32px 40px" }}>
            <div style={{ flex: 1 }}>
              <List title="金融解决方案" />
              <List
                title="其他解决方案"
                style={{
                  marginBlockStart: 32,
                }}
              />
            </div>

            <div
              style={{
                width: "308px",
                borderInlineStart: "1px solid " + token.colorBorder,
                paddingInlineStart: 16,
              }}
            >
              <div
                className={css`
                  font-size: 14px;
                  color: ${token.colorText};
                  line-height: 22px;
                `}
              >
                热门产品
              </div>
              {new Array(3).fill(1).map((name, index) => {
                return (
                  <div
                    key={index}
                    className={css`
                      border-radius: 4px;
                      padding: 16px;
                      margin-top: 4px;
                      display: flex;
                      cursor: pointer;
                      &:hover {
                        background-color: ${token.colorBgTextHover};
                      }
                    `}
                  >
                    <img src="https://gw.alipayobjects.com/zos/antfincdn/6FTGmLLmN/bianzu%25252013.svg" />
                    <div
                      style={{
                        marginInlineStart: 14,
                      }}
                    >
                      <div
                        className={css`
                          font-size: 14px;
                          color: ${token.colorText};
                          line-height: 22px;
                        `}
                      >
                        Ant Design
                      </div>
                      <div
                        className={css`
                          font-size: 12px;
                          color: ${token.colorTextSecondary};
                          line-height: 20px;
                        `}
                      >
                        杭州市较知名的 UI 设计语言
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        }
      >
        <div
          style={{
            color: token.colorTextHeading,
            fontWeight: 500,
            cursor: "pointer",
            display: "flex",
            gap: 4,
            paddingInlineStart: 8,
            paddingInlineEnd: 12,
            alignItems: "center",
          }}
          className={css`
            &:hover {
              background-color: ${token.colorBgTextHover};
            }
          `}
        >
          <span> 企业级资产中心</span>
          <CaretDownFilled />
        </div>
      </Popover>
    </div>
  );
};

const SearchInput = () => {
  const { token } = theme.useToken();
  return (
    <div
      key="SearchOutlined"
      aria-hidden
      style={{
        display: "flex",
        alignItems: "center",
        marginInlineEnd: 24,
      }}
      onMouseDown={(e) => {
        e.stopPropagation();
        e.preventDefault();
      }}
    >
      <Input
        style={{
          borderRadius: 4,
          marginInlineEnd: 12,
          backgroundColor: token.colorBgTextHover,
        }}
        prefix={
          <SearchOutlined
            style={{
              color: token.colorTextLightSolid,
            }}
          />
        }
        placeholder="搜索方案"
        bordered={false}
      />
      <PlusCircleFilled
        style={{
          color: token.colorPrimary,
          fontSize: 24,
        }}
      />
    </div>
  );
};


const Index = ():JSX.Element => {
  const [settings, setSetting] = useState<
    Partial<ProSettings> | undefined
  >({
    fixSiderbar: true,
    layout: "mix",
    splitMenus: true,
  });

  const [pathname, setPathname] = useState(
    "/list/sub-page/sub-sub-page1"
  );
  const [num, setNum] = useState(40);

    // 
    // useEffect
    useEffect(() => {
      // page loaded
      document.title = `page loaded!`;
    });
  
  return (
    <div
      id="test-pro-layout"
      style={{
        height: "100vh",
      }}
    >
      <ProConfigProvider hashed={false}>
        <ProLayout
          prefixCls="my-prefix"
          bgLayoutImgList={[
            {
              src: "https://img.alicdn.com/imgextra/i2/O1CN01O4etvp1DvpFLKfuWq_!!6000000000279-2-tps-609-606.png",
              left: 85,
              bottom: 100,
              height: "303px",
            },
            {
              src: "https://img.alicdn.com/imgextra/i2/O1CN01O4etvp1DvpFLKfuWq_!!6000000000279-2-tps-609-606.png",
              bottom: -68,
              right: -45,
              height: "303px",
            },
            {
              src: "https://img.alicdn.com/imgextra/i3/O1CN018NxReL1shX85Yz6Cx_!!6000000005798-2-tps-884-496.png",
              bottom: 0,
              left: 0,
              width: "331px",
            },
          ]}
          {...defaultProps}
          location={{
            pathname,
          }}
          siderMenuType="group"
          menu={{
            collapsedShowGroupTitle: true,
          }}
          avatarProps={{
            src: "https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg",
            size: "small",
            title: "七妮妮",
            render: (props, dom) => {
              return (
                <Dropdown
                  menu={{
                    items: [
                      {
                        key: "logout",
                        icon: <LogoutOutlined />,
                        label: "退出登录",
                      },
                    ],
                  }}
                >
                  {dom}
                </Dropdown>
              );
            },
          }}
          actionsRender={(props) => {
            if (props.isMobile) return [];
            return [
              props.layout !== "side" &&
              document.body.clientWidth > 1400 ? (
                <SearchInput />
              ) : undefined,
              <InfoCircleFilled key="InfoCircleFilled" />,
              <QuestionCircleFilled key="QuestionCircleFilled" />,
              <GithubFilled key="GithubFilled" />,
            ];
          }}
          headerTitleRender={(logo, title, _) => {
            const defaultDom = (
              <a>
                {logo}
                {title}
              </a>
            );
            if (document.body.clientWidth < 1400) {
              return defaultDom;
            }
            if (_.isMobile) return defaultDom;
            return (
              <>
                {defaultDom}
                <MenuCard />
              </>
            );
          }}
          menuFooterRender={(props) => {
            if (props?.collapsed) return undefined;
            return (
              <div
                style={{
                  textAlign: "center",
                  paddingBlockStart: 12,
                }}
              >
                <div>© 2021 Made with love</div>
                <div>by Ant Design</div>
              </div>
            );
          }}
          onMenuHeaderClick={(e) => console.log(e)}
          menuItemRender={(item, dom) => (
            <div
              onClick={() => {
                setPathname(item.path || "/welcome");
              }}
            >
              {dom}
            </div>
          )}
          {...settings}
        >
          <PageContainer
            token={{
              paddingInlinePageContainerContent: num,
            }}
            extra={[
              <Button key="3">操作</Button>,
              <Button key="2">操作</Button>,
              <Button
                key="1"
                type="primary"
                onClick={() => {
                  setNum(num > 0 ? 0 : 40);
                }}
              >
                主操作
              </Button>,
            ]}
            subTitle="简单的描述"
            footer={[
              <Button key="3">重置</Button>,
              <Button key="2" type="primary">
                提交
              </Button>,
            ]}
          >
            <ProCard
              style={{
                height: "200vh",
                minHeight: 800,
              }}
            >
              <div />
            </ProCard>
          </PageContainer>

          <SettingDrawer
            pathname={pathname}
            enableDarkTheme
            getContainer={() =>
              document.getElementById("test-pro-layout")
            }
            settings={settings}
            onSettingChange={(changeSetting) => {
              setSetting(changeSetting);
            }}
            disableUrlParams={false}
          />
        </ProLayout>
      </ProConfigProvider>
    </div>
  );
};

export default Index;

Links:

https://codesandbox.io/s/eoy3s9

https://procomponents.ant.design/en-US/components/layout?tab=api

element need to be sticked to bottom (position:absolute) vs part of the DOM (position:relative)

I have a requirement where element need to be sticked to bottom (position:absolute) vs part of the DOM (position:relative)

UseCase “footer” stick to bottom (position:absolute) when elementA and elementB are not in view. “footer” position relative when elementA is not in view, elementB is in view. “footer” position relative when elementA, elementB both in view.

tried waypoint, offsets. having jittery flashing footer when elementB comes into view while scrolling. I do not think observer api is helpful here.

Trying to implement a scoring system to a web-based trivia game

I am trying to implement a scoring system to a trivia game using java scrip and HTML. I got the code for the questions and all the containers in the HTML I just need a variable in the java script code that increments every time the user answers the question correctly and I need that variable to be displayed to the user. I tried declaring a variable in java script but it doesn’t change its value on a correct answer or at least that value is not displayed to the user. Here is my code:
HTML:

const startButton = document.getElementById('start-btn')
const nextButton = document.getElementById('next-btn')
const questionContainerElement = document.getElementById('question-container')
const questionElement = document.getElementById('question')
const answerButtonsElement = document.getElementById('answer-buttons')
var score = document.getElementById("score")

var score = 0;
document.write (score);


let shuffledQuestions, currentQuestionIndex

startButton.addEventListener('click', startGame)
nextButton.addEventListener('click', () => {
  currentQuestionIndex++
  setNextQuestion()
})

function startGame() {
  startButton.classList.add('hide')
  shuffledQuestions = questions.sort(() => Math.random() - .5)
  currentQuestionIndex = 0
  questionContainerElement.classList.remove('hide')
  setNextQuestion()
}

function setNextQuestion() {
  resetState()
  showQuestion(shuffledQuestions[currentQuestionIndex])
}

function showQuestion(question) {
  questionElement.innerText = question.question
  question.answers.forEach(answer => {
    const button = document.createElement('button')
    button.innerText = answer.text
    button.classList.add('btn')
    if (answer.correct) {
      button.dataset.correct = answer.correct
       
    }
    button.addEventListener('click', selectAnswer)
    answerButtonsElement.appendChild(button)
  })
}

function resetState() {
  clearStatusClass(document.body)
  nextButton.classList.add('hide')
  while (answerButtonsElement.firstChild) {
    answerButtonsElement.removeChild(answerButtonsElement.firstChild)
  }
}

function selectAnswer(e) {
  const selectedButton = e.target
  const correct = selectedButton.dataset.correct
  setStatusClass(document.body, correct)
  Array.from(answerButtonsElement.children).forEach(button => {
    setStatusClass(button, button.dataset.correct)
  })
  if (shuffledQuestions.length > currentQuestionIndex + 1) {
    nextButton.classList.remove('hide')
  } else {
    startButton.innerText = 'Restart'
    startButton.classList.remove('hide')
  }
}

function setStatusClass(element, correct) {
  clearStatusClass(element)
  if (correct) {
    element.classList.add('correct')
    score += 10
  
  } else {
    element.classList.add('wrong')
  }
}

function clearStatusClass(element) {
  element.classList.remove('correct')
  element.classList.remove('wrong')
}

const questions = [
  {
    question: 'What is 2 + 2?',
    answers: [
      { text: '4', correct: true },
      { text: '22', correct: false }
    ]
  },
  {
    question: 'Who is the best YouTuber?',
    answers: [
      { text: 'Web Dev Simplified', correct: true },
      { text: 'Traversy Media', correct: true },
      { text: 'Dev Ed', correct: true },
      { text: 'Fun Fun Function', correct: true }
    ]
  },
  {
    question: 'Is web development fun?',
    answers: [
      { text: 'Kinda', correct: false },
      { text: 'YES!!!', correct: true },
      { text: 'Um no', correct: false },
      { text: 'IDK', correct: false }
    ]
  },
  {
    question: 'What is 4 * 2?',
    answers: [
      { text: '6', correct: false },
      { text: '8', correct: true }
    ]
  }
]
*, *::before, *::after {
  box-sizing: border-box;
}

body {
  padding: 0;
  margin: 0;
  display: flex;
  width: 100vw;
  height: 100vh;
  justify-content: center;
  align-items: center;
  background-color: #4C8568
}

body.correct {
  color: green
}

body.wrong {
  background-color: red
}


.container {
  font-size: 20px;
  color: #B69E17;
  font-weight: bold;
  width: 800px;
  max-width: 80%;
  background-color: #5E6861;
  border-radius: 20px;
  padding: 10px;
  box-shadow: 0 0 10px 2px;
 
}

.box {
  width: 100px;
  border-radius: 20px;
  padding: 5px;
  color: black;
  background-color: white;
 
  
}

.btn-grid {
  display: grid;
  grid-template-columns: repeat(2, auto);
  gap: 10px;
  margin: 20px 0;
}

.btn {
  
  border: 1px solid hs1;
  background-color: #6C5F16;
  border-radius: 10px;
  padding: 5px 10px;
  color: white;
  font-weight: bold;
  font-size: 15px;
  outline: none;
}

.btn:hover {
  border-color: black;
}

.btn.correct {
  --hue: var(--hue-correct);
  color: green;
}

.btn.wrong {
  --hue: var(--hue-wrong);
  color: red;
}

.start-btn, .next-btn {
  font-size: 1.5rem;
  font-weight: bold;
  padding: 10px 20px;
}

.controls {
  display: flex;
  justify-content: center;
  align-items: center;
}

.hide {
  display: none;
}

html {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: green;
}

.points {
  position: absolute;
  top: 15px;
  right: 15px;
  
}

.points {
  display: flex; 
  color: white;
  width: 250px;
  padding: 10px 0;
  font-size: 30px;
}

  
<div class="container">
  <div id="question-container" class="hide">
    <div id="question">Question</div>
    <div id="answer-buttons" class="btn-grid">
      <button class="btn">Answer 1</button>
      <button class="btn">Answer 2</button>
      <button class="btn">Answer 3</button>
      <button class="btn">Answer 4</button>
    </div>
  </div>
  
  <div class="controls">
    <button id="start-btn" class="start-btn btn">Start</button>
    <button id="next-btn" class="next-btn btn hide">Next</button>
  </div>
  
</div>
    <div class="box">
       <div id="score">SCORE:</div>
          </div>      
                                                                                                             

Es findet nicht mein Hauptmenue.js [closed]

Ich programmiere erst seit kurzem und komme grad nicht weiter.

Ich arbeite an einem Projekt und irgendwie wird das Hauptmenue.js nicht mitintegriert. Ich habe jetzt mal nicht die anderen .js datein beigefügt da die grad keine rollen spielen.

Ich kriege es hin das Index mit Electron zu öffnen, dennoch erscheinen nur die drei Buttons, wenn ich drauf drücke passiert nicht sonderlich was. Der plan war das der Hauptmenue.js Skript sich dann öffnet.

Zudem sind folgende Fehler angezeigt im “browswer fenster”:

Unable to load preload script: C:UserskwanjOneDriveProjekteDD2preload.js
(
Error: module not found: ./Hauptmenue
    at preloadRequire (VM4 sandbox_bundle:2:82057)
    at <anonymous>:2:22
    at runPreloadScript (VM4 sandbox_bundle:2:82809)
    at VM4 sandbox_bundle:2:83068
    at VM4 sandbox_bundle:2:83223
    at ___electron_webpack_init__ (VM4 sandbox_bundle:2:83227)
    at VM4 sandbox_bundle:2:83350
(
Uncaught ReferenceError: require is not defined
    at renderer.js:2:20
Uncaught SyntaxError: Identifier 'Hauptmenue' has already been declared (at Hauptmenue.js:1:1)

Hier meine Codes:

index.js

const { app, BrowserWindow } = require('electron');
const path = require('path');

function createWindow() {
    const mainWindow = new BrowserWindow({
      width: 800,
      height: 600,
      webPreferences: {
        sandbox: true,
        nodeIntegration: true,
        preload: path.join(__dirname, 'preload.js') // Replace 'preload.js' with the filename of your preload script
      }
    });
  
    mainWindow.loadFile('index.html');
    mainWindow.webContents.openDevTools();
  }
  

// The following code creates the main window of the application using Electron. The window is set to 800 x 600 pixels and includes the nodeIntegration feature to allow the use of Node.js APIs in the renderer process. The window also loads the index.html file and opens the DevTools.

app.whenReady().then(createWindow);

// The app.whenReady() method waits until the app's ready event is emitted before creating the main window.

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// The app.on('window-all-closed') method listens for the window-all-closed event, which is emitted when all windows have been closed. If the platform is not macOS, the app quits.

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

preload.js

const Hauptmenue = require('./Hauptmenue');
const CharakterErstellung = require('./CharakterErstellung');
const Geschichte = require('./Geschichte');

window.Hauptmenue = Hauptmenue;
window.CharakterErstellung = CharakterErstellung;
window.Geschichte = Geschichte;

renderer.js

// renderer.js
const Hauptmenue = require('./Hauptmenue');
const hauptmenue = new Hauptmenue();

document.getElementById('charakterErstellung').addEventListener('click', () => {
  hauptmenue.charakterErstellung();
});

document.getElementById('spielLaden').addEventListener('click', () => {
  hauptmenue.spielLaden();
});

document.getElementById('geschichteAuswählen').addEventListener('click', () => {
  hauptmenue.geschichteAuswählen();
});

index.html

<!-- index.html -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Meine Anwendung</title>
  </head>
  <body>
    <button id="charakterErstellung">Charakter erstellen</button>
    <button id="spielLaden">Spiel laden</button>
    <button id="geschichteAuswählen">Geschichte auswählen</button>

    <!-- Binden Sie die renderer.js-Datei ein -->
    <script src="renderer.js"></script>

    <!-- Binden Sie die Hauptmenue.js-Datei ein -->
    <script src="./Hauptmenue.js"></script>
  </body>
</html>

Hauptmenue.js

const Hauptmenue = require('./Hauptmenue');
const hauptmenue = new Hauptmenue();

document.getElementById('charakterErstellung').addEventListener('click', () => {
  hauptmenue.charakterErstellung();
});

document.getElementById('spielLaden').addEventListener('click', () => {
  hauptmenue.spielLaden();
});

document.getElementById('geschichteAuswählen').addEventListener('click', () => {
  hauptmenue.geschichteAuswählen();
});

// The above code requires the Hauptmenue module and creates a new instance of it. It also adds event listeners to the three buttons on the web page, which call the corresponding methods of the hauptmenue object when clicked.

Hab schon einiges probiert, aber komme einfach nicht weiter. Habe mit verschiedenen Namen probiert etc. Mir fällt jetzt sonst kein weiter Weg ein.

why i am not able to change the source of image using DOM?

    
            <img id ="image" src="E:freecodecampprojectsReviewsfblack.jpg"   alt="">
            

—– HTML ENDS HERE —-

const reviews = [
    {
        id:1,
        photo : "E:freecodecampprojectsReviewsfblack.jpg",
        fullname: "Sara John",
        job: "UX DESIGNER",
        text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
    },
    {
        id:2,
        photo : "E:freecodecampprojectsReviewsfkorean.jpg",
        fullname: "Murakami",
        job: "GRAPHIC DESIGNER",
        text: "As designers attempting to creating functional work, oftentimes we are required to make our designs look as finished as possible. For example, if you are designing a brand new website for someone, most times you will have to make sure the prototype looks finished by inserting text or photos or what have you.",
    },
    
];

const profileImage = document.getElementById("image");




let currentItem = 1;

window.addEventListener("DOMContentLoaded",function(){
    const item = reviews[currentItem];
    profileImage.src = item.photo;
    
});

above is the full code of javascript file

Q. Inside function, all is working except profileImage.

In above profileImage.src = item.photo; should change the profile photo.

If toggle one is being switched off by the user then toggle two should be switched on

I am quite new to knockoutjs and I am trying to create two toggles. When toggle one is switched off and then toggle two is switched off by the user, toggle one should be switched on and vice versa.

function alternatetogglesWithOrWithoutCreditRequests() {
            if (!viewModel.withPendingCreditRequests()) {
                viewModel.withoutPendingCreditRequests(true)
            }
            else if (!viewModel.withoutPendingCreditRequests()) {
                viewModel.withPendingCreditRequests(true)
            }
        }

This code above does not work all the time because in both cases the withPendingCreditRequests and the withoutPendingCredit observables are false.

Below is the html for the toggles:

    <div>
         <toggle-switch params="enable: invoiceFiltersActive, checked: withPendingCreditRequests, label: 'With Pending Credit Requests'"> 
         </toggle-switch>
    </div>
    <div>
         <toggle-switch params="enable: invoiceFiltersActive, checked: withoutPendingCreditRequests, label: 'Without Pending Credit Requests'">
         </toggle-switch>
    </div>

Cubejs: use data from related table

I have the following schemas:
Project and Orders, with Orders being a hasMany relationship to Projects.

I need to create a measure in Projects that sums the column fee from all related Orders, so I have done the following

profit: {
      type: `sum`,
      sql: `${Orders}.fee`,
      shown: true
    }

which produces the error:

Error: 'Projects.profit' references cubes that lead to row multiplication. Please rewrite it using sub query.

Dynamic Object Property Question with Reduce Function

I wanted to ask a simple question about dynamic object properties.
In this example function I made, I noticed that I need square brackets between the cur.name variable but not for cur.age in the return statement. I found that it was something about dynamic object properties but was unsure of when I exactly need square brackets for parameters. Could I ask when I need square brackets?

Here is an example function:

const array = [
  {name: 'A', age: 1},
  {name: 'B', age: 2},
  {name: 'C', age: 3},
];

const example = (array) => {
    return array.reduce((acc, cur) => {return {...acc, [cur.name]: cur.age} }, {})
}

console.log(example(array));

//Output that I want is {A: 1, B: 2, C: 3} and it works.