How can i use variable inside Vanilla JavaScript class to make a function based on boolen

i have a JS Class which is making a function of giving a border to an element when i click to another element. That means when i click on .trigger class element, it will give a border to .content class element. But this function only should be happen based on a Boolean condition. If Boolean is Yes it should be give border, other wise i should not work. My code is works when i set the method inside the constructor parenthesis with this keyword and i can also declare variable there. But I need the method outside the constructor based on my other code. So how can i possible to declare vaiable outside the constructor and inside the class. I need this using Class approach based on my project. My code is as follows. Hope someone can help me on this. Thanks in advance!

class ParentSelector {
    constructor(trigger, content, condition) {
        this.trigger = document.querySelector(trigger);
        this.content = document.querySelector(content);
    }

    let outline = condition;

    makeOutline(){
        this.trigger.addEventListener("click", (e) => {
            if (condition) {
                e.target.nextElementSibling.style.border = "2px solid red";
            }
        })
    }    
    
}

let a = new ParentSelector(".trigger",".content", true);
a.makeOutline();
<div class="one">
<div class="trigger">Trigger</div>
<div class="content">Content</div>
</div>

One tab open at one time for accordion

I have this accordion opening all tabs at same time but i want it to open one tab at one time and when you click on other tab it closes the previous tab.
I tried to play with the javascript but only I can get is the tab not opening completely.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  });
}
<button class="accordion">Section 1</button>
<div class="panel">
  <p>CONTENT 1</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel">
  <p>CONTENT 2</p>
</div>

<button class="accordion">Section 3</button>
<div class="panel">
  <p>CONTENT 3.</p>
</div>

querySelector returned empty element

I have problem that when my code auto refreshes after I saved the file on VS Code, theText and theBtn returns the targeted elements and the page displays the content and everything works fine. But whenever I refresh the page manually, the page displays the content, but when I clicked theBtn element to expand the text, the theText and theBtn becomes empty and the page failed with an error saying “cannot read property of undefined”.

I have been trying to find why, but I could not. Someone please help.
Thank you.

import { React, useEffect, useState } from 'react';
    import places from '../data/places';


const Tours = () => {
return (
    <>
        <div className="my-20 mx-auto bg-blue-100 " style={{ height: "100%" }}>
            <h1 className="text-5xl capitalize text-center font-semibold">our tours</h1>
            <hr className="w-20 place-self-center mx-auto border-2 mb-12 mt-2 border-green-600" />
            <Tuor cTime={new Date().getTime().toString()} />
        </div>
    </>
)
}

const Tuor = (props) => {

const [tuors, setTours] = useState(places);

 const theText = document.querySelectorAll(".theText")
 const theBtn = document.querySelectorAll(".theBtn")
        console.log(theText);
        console.log(theBtn);


const expandText = (index) => {

    if (theBtn[index].innerHTML === "read more") {
        theText[index].style.maxHeight = "50rem";
        theBtn[index].innerHTML = "show less";
    } else if (theBtn[index].innerHTML === "show less") {
        theText[index].style.maxHeight = "6rem";
        theBtn[index].innerHTML = "read more";

    }
}

const removePlace = (id) => {
    const newTours = tuors.filter((place) => {
        return place.id !== id;
    });
    setTours(newTours);
}
return (
    <>
        {
            tuors.map((place, index) => {
                let price = new Intl.NumberFormat().format(place.price);
               
                return (
                    <>
                        <div key={index} className="flex flex-col w-2/4 mx-auto bg-white shadow-2xl mb-10">

                            <div>
                                <img src={place.image} alt={place.title} />
                            </div>

                            <div className="flex mt-10">
                                <div className="flex justify-start w-3/4 pl-10">
                                    <p className="tracking-widest capitalize font-bold">{place.title}</p>
                                </div>
                                <div className="flex justify-end w-1/4 pr-10"><p className="bg-blue-50 tracking-wider p-1 rounded-lg font-bold text-blue-400">N{price}</p></div>
                            </div>
                            <div className="my-5 px-10 py-2">
                                <p className="text-gray-500 theText">{place.description}</p><button className="text-blue-500 capitalize theBtn" onClick={() => expandText(index)}>read more</button>
                            </div>
                            <button className="ring-1 ring-red-600 text-red p-1 rounded-sm w-48 mx-auto capitalize my-12" onClick={() => removePlace(place.id)}>not interested</button>
                        </div>

                    </>
                )
            })
        }
    </>
)
}


export default Tours;

checking file size before uploading image using multer

how can I use the submiting data related to image pass to server using multer before uploading it to disk .Is it possible ? if not then please give me another solution.
I want to check the size of file its should be at least 4mp resolution ,if its has lesser then that the images should not be uploaded and send the error msg

exports.uploadimg=(req,res,next)=>{
  
    uploadphoto(req, res, (err) => {
        if (err) {
            res.render("upload")
        }
        else {


    
            

          


           
            res.send("photo uloaded")
        }
    })

Get locally instanced ‘this’ for native code prototypes [duplicate]

I’m trying to extend a built-in javascript function via prototype, but when I attempt to refer to this, Window is returned. Given that I don’t really have access to rewrite the implementation, are there any ways to get around this?

Specifically I’m trying to extend URLSearchParams in such a way that it unsets values properly. Something like:

URLSearchParams.prototype.setOrUnset = (key, val) => {
    if(val){
        this.set(key, val)
    } else {
        this.delete(key)
    }
}

how to check after deleting one element from array

hello i have creating a pragam that delete one array from another but. And it works fine i think but if i put 2 same value simultaneously, it remove only one value because of second argument of splice function. How can i check after deleting a element again if there any other number left my code is below.

const arr1 = [1, 2, 2, 3, 5, 2, 3, 7];
const arr2 = [2, 3];

let countArr = [];
for (let i = 0; i < arr2.length; i++) {
  for (let j = 0; j <= arr1.length; j++) {
    if (arr1[j] === arr2[i]) {
      arr1.splice(j, 1);
    }
  }
}
console.log(arr1);
<!DOCTYPE html>
<html lang="en">

<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>Document</title>
</head>

<body>

  <script src="demo.js"></script>
</body>

</html>

Moving my Node.js app to Express, getting Document Null errors

I have my fully working app here that I’m trying to host on a localhost server using Express.js

https://jsfiddle.net/mostafa91/6axesy2t/2/

Here is my server.js that I run with “node server.js”:

const express = require('express');
const app = express();
const port = 2525;

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/Gameboard.html');
});

app.listen(port, () => {
    console.log(`Tic-Tac-Toe listening at http://localhost:${port}`);
});

app.use(express.static('public'));

I keep getting errors when I try to play the game (vs. Players option):

Uncaught TypeError: Cannot read properties of null (reading 'classList')
    at setBoardHoverClass (Gameboard.js:74)
    at startGame (Gameboard.js:32)
    at Gameboard.js:20

I’ve included my file structure as well: Here

Vanilla JS getting all links under span using XPath and foreach loop

Het all I can not seem to get this below code to work:

var links = doc.DocumentNode.SelectSingleNode("/html/body/div[1]/div/div[4]/div/div/div[2]/div[2]/span[1]");

foreach (HtmlNode item in table.SelectNodes("//span[1]/descendant::a[starts-with(@href,'/photo')]"))
{
    console.log("test");
}

It keeps telling me:

Uncaught SyntaxError: missing ) after argument list

It looks like all my “)” are present and in the correct spots?

the HTML that I am getting the links from looks like this:

<span>
  <a href="/photo356.png" class="_4dvp" id="_D9">
    <div class="_403j">
      <i class="im_2sxw" style="width:100px;height:100px;" aria-label="pic" role="img"></i>
      <div class="_5fef">
        <div class="_5feg" role="link" aria-label="25">
          <i class="imgMGdk7"></i>25
        </div>
        <div class="fezg" role="link" aria-label="15">
          <i class="_imgsp_l0"></i>15
        </div>
      </div>
    </div>
  </a>
  <a href="/photo17814561.png" class="_39pvp" id="u3_sz">
    <div class="_403j">
      <i class="imgxw" style="width:100px;height:100px;" aria-label="pic61" role="img"></i>
      <div class="_5f">
        <div class="fzeg" role="link" aria-label="23">
          <i class="_img2e1b6"></i>23
        </div>
    ...etc....

the XPath starts at the . The XPath is this:

/html/body/div[1]/div/div[4]/div/div/div[2]/div[2]/span[1]

But like I said above I just get that JS error. I’m not even sure my XPATH logic is even correct since I’m not able to pass this error and continue on…

Help would be great!

How do I get a js library without import

I want to make a js library, and I have all the code. Libraries like Jquery can let you do like

<script src = "..."></script>
<script>
//uses the library
</script>

without the import * from JQuery.
How can I do this without declaring the library a modular or importing?

Remove an HTML tag from Div [closed]

I use a WYSIWYG editor in my website. It has the option of changing the font-size and fontcolor of the chapter.

However, I want to make sure that if the user desires, they can actually override the font settings while reading it.

I know I can just get the innerHTML and replace the font-size and color attributes from it. However, it may be possible that font-size and color may actually be part of the text instead of HTML tag.

So how can I remove these attributes from HTML without affecting the main text?

How to dynamically add a changeable size canvass to pdf?

I am using Html2Canvas and jsPDF to create a canvass from a hidden div content, the core issue here is when I want to mount the canvass on the pdf,

what I am considering is, the items div could have 1 item and could have 1000, what I want to implement is the more items the smaller the items get on the canvass so they will always fit no matter how big or how small, any idea how to solve this? , another case here is how to create another pdf page if items don’t fit on a single page in case my previous question is impossible to implement.

const html2canvasfn = () => {
    html2canvas(
      document.getElementById('clone')!,
      {
        onclone: function (clonedDoc) {
          clonedDoc.getElementById('clone')!.style.display = 'flex';
        },
      }

    ).then((canvas) => {
      document.getElementById('clone')!.style.display = 'none';
      
      const imgData = canvas.toDataURL('image/png');
      // A4 size
      var doc = new jsPDF('p', 'mm', 'a4');
      
      var width = doc.internal.pageSize.getWidth();
      var height = doc.internal.pageSize.getHeight();
      let w = document.querySelector('#clone')!.scrollWidth;
      let h = document.querySelector('#clone')!.scrollHeight;
      
      doc.addImage(imgData, 'PNG', 30, 0, /*w!*/ /*1500 / 10*/ w! /*width*/ /*w!*/, /*height*/ /*h!*/ h!);
      doc.save('doc.pdf');
  
    });
  };

return (
<div style={{ textAlign: 'center' }}>
<Container id='clone' style={{ display: 'none', flexDirection: 'column', justifyContent:                'center', textAlign: 'center', minWidth: 900 }}>
{Object.entries(groupItems(context.exercises[mContext.modal.id])).map(([groupName, items]:             Mapped, i) => (
<div>
<ul>
{i + 1}
{Icons[groupName]}
{groupName}
</ul>
{items.map((el) => (
<li
el.text
/>
))}

</div>
))}
</Container>
</div>
  );
};

Importing “@daily-co/daily-js” into SvelteKit app throws “global is not defined” error

What I tried:

  1. I tried work around it via if (browser), more specifically{
    if (!browser) { let DailyIframe = await import('daily-co/daily-js) } in the load function inside <script context="module"> ) so the code is always executed on the server). Then pass it as a prop to a component. However, although it worked on the server, the local dev environment re-runs the load function (which has to return an empty prop as it never imported anything) and overrides DailyIframe’s value (might be a bug with Vite/SvelteKit).

  2. I tried to import the library in an end-point e.g. api.json.js instead, which is always executed on the server. However, it has to return a json, and I can’t pass an entire library variable onto it.

After research
It seems like a combination of problems from Vite, SvelteKit and certain libraries where global is undefined: SvelteKit With MongoDB ReferenceError: global is not defined)

But I cannot use his solution of putting it in an endpoint, because I need the DailyIframe and the mic audio stream from the client to create a video conference room

Also, why would certain libraries Daily (and looking at other related Stackoverflow posts, MongoDB) throw this error in the first place, while other libraries are safe to use?

Anyway suggestion is appreciated!

change button icon Bootstrap 5 without jquerry

I’m trying to change the button’s icon and text onclick in a project (node js, javascript) using Bootstrap 5 (without jquery).
There are dozens of example of it, all using jquery with older versions of Bootstrap. Is there a way to do it in latest Bootstrap (without jquery)?