Is it possiable to get source of a HTML element of a partiulcar area/part of a web page?

Is it possible to get the source of an HTML element of a particular area/part of a web page? Like sometimes we open our browser open a website hover over a button or element and inspect it and we can see all the code for example <div class="fs-body2 bb bc-black-225 bg-black-100 p12"> Introduce the proble </div> and we can see that particular element code in my case I hover over ‘ Introduce the problem’ and just inspect it and I get that source.

Currently, my code doesn’t work on every HTML code it return null in most cases if the HTML code is too large.

import fs from "fs";
import { JSDOM } from "jsdom";

function findTextInHTML(filePath, targetText) {
  const htmlCode = fs.readFileSync(filePath, "utf8");
  const dom = new JSDOM(htmlCode);
  const document = dom.window.document;

  function searchText(element) {
    if (element.textContent.includes(targetText)) {
      return element;
    }

    if (element.outerHTML.includes(targetText)) {
      for (const child of element.children) {
        const result = searchText(child);
        if (result) {
          return result;
        }
      }

      return element;
    }

    return null;
  }

  const foundElement = searchText(document.body);

  return foundElement ? foundElement.tagName.toLowerCase() : null;
}

const htmlFilePath = "index.html";
const searchText = "Get Started";
const result = findTextInHTML(htmlFilePath, searchText);
console.log(result);

How do I create a 3d array in JavaScript initialised to be full of zeroes, with XYZ dimensions 5x5x64

I’ve written what i thought would create an array of 5 arrays each containing 5 arrays of 64 zeroes, but when i write the resulting array to the console, i do not get what i expected to see, yet the code makes sense to me.

Here is my code:

    const C = new Array(5);

    for (let x = 0; x < 5; x++) {
        for (let y = 0; y < 5; y++) {
            for (let z = 0; z < 64; z++) {
                C[x,y,z] = 0;
            }
        }
    }

    console.log(C);

logging C presents me with one array of 64 zeroes. What is wrong?

how to handle click event inside html from js and external js function

i have external file for templates i want to adding the templates in it but when i adding the onclick functoin its show error massage the handleClickCard not defind

import { handleClickCard } from "../../../script.mjs";

function templateCard(item, condition, idUpdate, id, title, tags) {
  const card = `
<div class="card" >
    <div class="card-header">                 
        <span onclick="showuserinfo('${encodeURIComponent(JSON.stringify(item),
    )}')" style="cursor: pointer;"><strong>${item.author.username
    }</strong>
        </span>
        ${condition
      ? `<button class="btn btn-danger mx-2" style="float: right;" onclick={handleclickdeletebutton('${idUpdate}')}>delete</button>`
      : ""
    }
        ${condition ? `<button class="btn btn-primary" style="float: right;" onclick="handleclickeditbutton('${encodeURIComponent(JSON.stringify(item),)}')">edit</button>`
      : ""}
    </div>

     <!-- the problem in here and there is another problem in the file but its the same solution for this problem -->
    <div class="card-body" onclick="handleClickCard(${id})">

        </div>
    </div>
</div>
  `;
  return card;
}
export { templateCard };

and handleClickCard in another file i export it

export const handleClickCard = () => {
    console.log("handle click")
}

and the error massage that show :

Uncaught ReferenceError: handleClickCard is not defined

so how to perform the function from the external templates file ????

In a RESTful API how should you handle optional query parameters

I’m currently dealing with a .net API that aims to be RESTful. One of the endpoints I’m working with has two optional query parameters. The following usage is allowed:

/endpoint/search
/endpoint/search?from=01/02/23
/endpoint/search?from=01/02/23&to=01/03/23

This endpoint however returns a 400 when you do not provide a value for these optional query params but the keys still exist. Since I primarily work in JS, having the query params either not exist or have a value of undefined are realistically the same thing this seems odd to me that it would return a 400.

I.e.

/endpoint/search?from=undefined&to=undefined // 400 response

I’ve tried to scour the internet for an answer. I’ve looked into OpenAPI specification and the REST rfc but I can’t find any relevant passages. I’m of the opinion this is making an endpoint overly restrictive and it should handle undefined as a value. What is the correct approach as per spec if possible?

Transfer overflowing HTML element children inside another div

I’m currently developing a client-side javascript program that allows users to preview documents for printing in the browser via an API call.
The goal is to display the documents in A4 format, each containing a preview of HTML content extracted from a JSON file obtained through the API.
An example of the HTML structure i obtain:

<div class="a4" style="padding: 20px" size="A4" contenteditable="true" fileid="1">
    <div class="content" fileid="1" contentid="1">
        <p class="paragraph-wrapper" lang="it-IT" align="left">
            <span style="font-family: Arial, serif;">
                <span style="font-size: small;">
                    <span style="font-size: small;"> 
                        Some text here1
                    </span>
                    <span style="font-size: small;"> 
                        Some text here2
                    </span>
                    <span style="font-size: small;"> 
                        Some text here3
                    </span>
                </span>
            </span>
        </p>
        <p class="paragraph-wrapper" lang="it-IT" align="left">
            <span style="font-family: Arial, serif;">
                <span style="font-size: small;">
                    <span style="font-size: small;"> 
                        Other text here1
                    </span>
                    <span style="font-size: small;"> 
                        Other text here2
                    </span>
                    <span style="font-size: small;"> 
                        Other text here3
                    </span>
                </span>
            </span>
        </p>
    </div>
</div>

I uploaded an image to provide more context.
enter image description here

The main issue I’m encountering arises when the text within one of the HTML blocks exceeds the maximum height of the container (.content), as indicated by the current display with a blue border. Currently, I’m addressing this problem by managing the transfer of a node from one page to another.

My starting approach involves iterating through nodes with the .paragraph-wrapper class. When one of these nodes reaches the maximum height, I add it to a new dynamically created .a4 page. However, iterating the nodes in its entirety, I lose precision in the text positioning within the new block, especially if the text/child nodes inside the parent node is/are a lot.

So, I’m looking for a way to split a container node, such as .paragraph-wrapper, into two distinct nodes if one of its children exceeds the bottom border of the .content container. Each new node should retain the same parent divs as the original node and the associated inline styles.

An example of what I would like to achieve starting from the previous code:

<div class="a4" style="padding: 20px" size="A4" contenteditable="true" fileid="1">
    <div class="content" fileid="1" contentid="1">
        <p class="paragraph-wrapper" lang="it-IT" align="left">
            <span style="font-family: Arial, serif;">
                <span style="font-size: small;">
                    <span style="font-size: small;"> 
                        Some text here1
                    </span>
                    <span style="font-size: small;"> 
                        Some text here2
                    </span>
                    <span style="font-size: small;"> 
                        Some text here3
                    </span>
                </span>
            </span>
        </p>
        <p class="paragraph-wrapper" lang="it-IT" align="left">
            <span style="font-family: Arial, serif;">
                <span style="font-size: small;">
                    <span style="font-size: small;"> 
                        Other text here1
                    </span>
                    <span style="font-size: small;"> 
                        Other text here2
                    </span>
                </span>
            </span>
        </p>
    </div>
</div>
***Here finish the first A4 page***


***Here start the second A4 page***
<div class="a4" style="padding: 20px" size="A4" contenteditable="true" fileid="1">
    <div class="content" fileid="1" contentid="2">
        <p class="paragraph-wrapper" lang="it-IT" align="left">
            <span style="font-family: Arial, serif;">
                <span style="font-size: small;">
                    <span style="font-size: small;"> 
                        Other text here3
                    </span>
                </span>
            </span>
        </p>
    </div>
</div>

A portion of my current code:

const content = document.querySelectorAll('.content');
const a4HeightWithoutPadding = evaluateContentHeight();
const lastContent = content[content.length - 1];

staticNodeArray.forEach(node => {
    // Append node to last content element
    lastContent.appendChild(node);

    node.className = 'paragraph-wrapper';

    const nodeOffsetBottom = node.offsetTop + node.offsetHeight;

    // If the parent node reaches the bottom side of .content, make a new A4 page
    if (nodeOffsetBottom > a4HeightWithoutPadding) {
        // Increment contentId for new page
        contentId += 1;

        // Create a new A4
        const newPage = createNewPage(fileId, contentId);

        // Append the A4 to the container
        container.appendChild(newPage);

        // Moving the overflowed content to the new A4
        const newContent = newPage.querySelector('.content');
        newContent.appendChild(node);
    }
});

// Create a new A4 page
function createNewPage(fileId, contentId) {
    const newA4Page = document.createElement('div');
    newA4Page.className = 'a4';
    newA4Page.setAttribute('style', 'padding: 20px');
    newA4Page.setAttribute('size', 'A4');
    newA4Page.setAttribute('contenteditable', 'true');
    newA4Page.setAttribute('fileId', fileId);
    newA4Page.innerHTML = `<div class="content" fileId=${fileId} contentId=${contentId}></div>`;

    return newA4Page
} 

function evaluateContentHeight() {
    const a4NodeList = document.querySelectorAll('.a4');

    // The last A4 created
    const a4 = a4NodeList[a4NodeList.length - 1];    

    // Calculate the A4 height
    const a4Height = a4.clientHeight;

    // Calculate the value of top and bottom padding
    const style = window.getComputedStyle(a4);
    const paddingTop = parseFloat(style.paddingTop);
    const paddingBottom = parseFloat(style.paddingBottom);
    
    // Calculate the final value of A4 height without the padding of the A4 
    const a4HeightWithoutPadding = a4Height - paddingTop - paddingBottom;
    
    return a4HeightWithoutPadding
}

Goggle Apps Script integration with Zabbix

I made an item in zabbix that runs a local PS1 file on the host machine

This is the item, when I access the specific Host and use the execute now function it works perfectly and runs the ps1 file

I needed to make Apps Script carry out this process of executing the item on a specific host (I would pass the host to the code and it to Zabbix).

is it possible to do that?

I created a zabbix API token and tried to run this item but without success, I didn’t find any video or documentation that does something similar

How to redirect PWA to new server after being opened?

this is my first post here.
I’m working on a group school project and made a PWA which is hosted on an external Cloudflare server with a certificate. For the duration of testing, the PWA sent data to that server through NodeJS. Now, after installing the PWA on a mobile device, I would like it to communicate with another server instead, a Raspberry PI with a fixed IP acting as a Wifi hotspot in order for the PWA to send data in the database it’s hosting, and effectively only keep the original server as the server that permits downloading and installing the PWA on devices.

Now my issue is, when I change the NodeJS code in the PWA to indicate which server it’s supposed to establish a connection with, the PWA still communicates with the server hosting it instead of contacting the new server. I tried changing the ip address and port in the PWA’s NodeJS code to indicate the new server it’s supposed to send data to, but when testing, it still sends its data to the host server instead of establishing a new connection to the rpi server.

All help is appreciated.

Resolving MODULE_NOT_FOUND Error for Internal Modules with TypeScript Path Aliases in AWS CDK during synthesis/deploymentt

I’m working on an AWS CDK project using TypeScript and encountering an issue with module resolution when running cdk synth or cdk deploy (the build is successful). My project structure includes internal modules that I’m trying to import into my CDK stacks, but I receive a MODULE_NOT_FOUND error during synthesis/deployment.

project structure

tsconfig.json

stack.ts

constant.ts

error message

Attempts to Resolve:

  1. I’ve verified the file paths and made sure that constant.ts exists at the specified location.
  2. I’ve tried using both relative(../common/type/constant) and absolute import (common/model/constant) paths.
  3. Running tsc directly compiles without any issues, but cdk synth or cdk deploy throws the error.
  4. I’ve also tried clearing node_modules and reinstalling, with no success.

I suspect the issue might be related to how the CDK CLI handles TypeScript path aliases or possibly how my TypeScript project is configured. However, I’m not sure how to diagnose or fix the issue to allow my CDK application to correctly resolve and import these internal modules.

Questions:

  1. How can I adjust my TypeScript or CDK configuration to resolve this issue?
  2. Is there a step I’m missing in the process to ensure the CDK CLI can handle TypeScript path aliases correctly?
  3. Are there known limitations or considerations with the AWS CDK and TypeScript imports that I should be aware of?
  4. Any guidance, diagnostic tips, or insights into how the AWS CDK and TypeScript work together in this context would be greatly appreciated.

How to change php Session variables after checkbox click

As stated, I have a website written in php with a checkbox and I’m trying to store its state between pages. Maybe it’s me being still new to javascript and php but I cannot get it to work

Below is my code (simplified):

one.php:

<?php session_start(); ?>
<html>
  <head>        
    <script>
        checkbox = document.getElementById('vehicle_toggle');
        checkbox.addEventListener('change', e => {
            if(e.target.checked){
                $_SESSION["favcolor"] = "red";
            } else {
                $_SESSION["favcolor"] = "green";
            }  
        });      
    </script>        
  </head>
  <body>
    <?php
      $_SESSION["favcolor"] = "red";
      print_r($_SESSION);
    ?>
    <input type="checkbox" id="vehicle_toggle" name="vehicle_name" value="Bike"  checked="checked">
    <label for="vehicle_toggle" class="vehicle_label">bike</label><br>        
    <a href="two.php">two</a>
  </body>
</html>

two.php:

<?php session_start(); ?>
<html>
  <body>
    <?php echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>"; ?>
  </body>
</html>

No matter the state of the checkbox on “one.php”, the color/state that is stored (and therefore printed for “two.php”) is the initial “red”. I’ve tried several different ways to write the javascript snippet but the output is always the same.

Thank your for your help!

revalidateTag/revalidatePath in sever actions updates the UI without visiting the page, why?

revalidateTag/revalidatePath “only invalidates the cache when the path is next visited in Next.js” (https://nextjs.org/docs/app/api-reference/functions/revalidatePath), and they work fine inside server actions for data revalidation and UI update when the page is navigated to. The bit I do not follow is why they also working producing a desired outcome of revalidating and updating UI when we are performing data mutation (like adding product) on the page that displays data, meaning that we are not navigating to a new page after performing a mutation yet apparently cache on the page we are currently on gets purged, data gets revalidated and UI updated. One answer to that is that “Server Actions integrate with the Next.js caching and revalidation architecture. When an action is invoked, Next.js can return both the updated UI and new data in a single server roundtrip.” (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations), and yes it does make sense only how does the next.js knows which ‘updated UI’ is supposed to send back? updated UI in terms of server component means some form of html that is ready to be displayed, and we can have many pages that are displaying data that our revalidateTag/revalidatePath is revalidating, one server actions can be imported to many different components and yet er get the specific html update relevant for our page without navigating to that page? To reiterate my problem is that I understand the when we navigate to new page then we can get the updated UI, but when we are already on the page and display data on it and perform mutation on it (given that we can be displaying the same data on many pages) how do we get the updated UI in the server action return trip for our desired page?

mongoose and express i want user related data in comment modal

I have a user ,post,comment modal

This is my comment modal

import mongoose from "mongoose";

const CommentSchema = new mongoose.Schema({
  postId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Post",
  },
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  content: {
    type: String,
    required: true,
  },
  image: {
    type: String,
  },
  likes: {
    type: Array,
    default: [],
  },
});

export default mongoose.model("Comment", CommentSchema);

and this is my addComment controller

export const addComment = async (req, res) => {
  try {
    const post = await Post.findById(req.body.postId);
    if (!post) {
      return res.status(404).json({ message: "Invalid Post Id" });
    }
    const comment = await new Comment(req.body);
    await comment.save();
    res
      .status(200)
      .json({ success: true, message: "Comment added Successfully!" });
  } catch (err) {
    res.status(500).json({ message: "Internal Server Error!" });
  }
};and this is my getComments controller

export const getAllCommentsOfPost = async (req, res) => {
  try {
    const post = await Post.findById(req.body.postId);
    if (!post) {
      return res.status(404).json({ message: "Invalid Post Id" });
    }
    const comments = await Comment.find({ postId: req.body.postId });
    res.status(200).json({ success: true, comments: comments });
  } catch (err) {
    res.status(500).json({ message: "Internal Server Error!" });
  }
};

This is my response

{
    "success": true,
    "comments": [
        {
            "_id": "65f2eec753e8de0aa1fffb26",
            "postId": "65f2e983f80127323fc86d8e",
            "content": "bad",
            "likes": [],
            "__v": 0
        }
    ]
}

in the response i am only getting postId , why am i not getting userId despite mentioning userId in comment modal and referenced it to user Modal and also how can i get the username as well .I need both username and userId in comments modal, can you guys tell me ways to do it?

How to open a page in a new tab after finalize purchase in woocommerce

How can I set up my checkout page so it opens in a new tab while still maintaining the regular WooCommerce behavior when the user presses the confirm purchase button?
I want to add a new method to the WooCommerce button so it opens a new tab.

I tried this in a Elementor HTML block:

<script>
document.addEventListener('DOMContentLoaded', function() {
    var abrirContratoButton = document.getElementById('place_order');
    if (abrirContratoButton) {
        abrirContratoButton.addEventListener('click', function(event) {
            //event.preventDefault();

          
            var firstName = document.getElementById('billing_first_name').value;
            var lastName = document.getElementById('billing_last_name').value;
            var cpfCnpj = document.getElementById('billing_cpf_cnpj').value;

            
            localStorage.setItem('billing_first_name', firstName);
            localStorage.setItem('billing_last_name', lastName);
            localStorage.setItem('billing_cpf_cnpj', cpfCnpj);

            
            window.location.href = abrirContratoButton.getAttribute('href');
        });
    }
});
</script>