Get DOM position by string index javascript

I am trying to find a way to get any parent (or child) element in HTML structure that is loaded into string by index. Keep in mind that string index is all I have. No tag name, class or id.

Supposes I have following stored in html variable, but the html would be usually much more complicated :

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>

Now I would like to be able to get something like following:

body > h1

Using something like html[63]

The problem here is that user can add any index number they want. So for example index number inside tag itself.

Right now I am using CodeMirror 6 for retrieving the string index by clicking into form if that helps.

how to fix ReferenceError: document is not defined?

js code

const inputEl = document.getElementById("input-el")

for this code console is showing error about document not defined, can anyone help how to solve this?

html code:

<input type="text" id="input-el">

ReferenceError: document is not defined
at Object. (c:UsersUserDesktopCounter jsChromeExtensionindex.js:2:17)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47

“No Exports Main Defined In” Error Node.js

I’m trying to make a simple api with js. But i keep getting this stupid error. NOTE: This is my first time programming in js.

Code:

const express = require('express')
const app = express()
const { Canvas } = require('canvas-constructor')
const canvas = require('canvas')

app.get('/:feed', async (req, res) => {

    const img = await canvas.loadImage('https://i.pinimg.com/originals/30/82/b0/3082b0354572c4d37af6994b4e8baa43.png')

    let image = new Canvas(670, 435)
    .printImage(img, 0, 0, 670, 435)
    .setTextFont('28px Impact')
    .printText(req.params.feed, 40, 150)
    .toBuffer();

    res.set({'Content-Type': 'image/png'})
    res.send(image)//sending the image!

})

app.listen(8080)

Error:

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in /home/runner/ScarceExcellentVariables/node_modules/canvas-constructor/package.json
    at new NodeError (node:internal/errors:371:5)
    at throwExportsNotFound (node:internal/modules/esm/resolve:440:9)
    at packageExportsResolve (node:internal/modules/esm/resolve:692:3)
    at resolveExports (node:internal/modules/cjs/loader:482:36)
    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)

If anyone could help me i’d appreciate it

Edit specific part of an image CSS/JS [closed]

I’ve this image. Image example
I’d like to allow my customer to change the different colors of the picture.
So we’d have two colors picks, one for black, one for pink.
When the customer changes the color, the picture changes at the same time.

Do you know a library that I can use to do that?
Maybe something that detects pink pixels and replace them or something like that?

Thank you very much

Item doesn’t want to be pushed into an array

I am developing a discord bot that allows you to mine for resources, but I can’t get the code to work. It’s logging the actual items, but it just doesn’t add the items to the array, which is why I can’t map it into a string.

Code:

module.exports.addItem = async (client, user, item, amount, interaction) => {
    if(!client instanceof Client) throw new Error("Client is not an instance of Discord.js Client");
    if(!user instanceof User) throw new Error("User is not an instance of Discord.js User");
    if(!item) throw new Error("Item is not defined");
    if(!amount) throw new Error("Amount is not defined");
    if(typeof amount !== "number") throw new Error("Amount is not a number");
    if(!interaction) throw new Error("Interaction is not defined");
    if(!interaction instanceof Interaction) throw new Error("Interaction is not an instance of Discord.js Interaction");

    const userFound = await client.database.user.findOne({ userID: user.id });
    if(!userFound) return interaction.followUp({ content: `You haven't started your journey yet!` });

    const itemFound = userFound.inventory.find(i => i.name === item.name);
        if(!itemFound) {
            await client.database.user.findOneAndUpdate(
                {
                    userID: user.id,
                }, {
                    userID: user.id,
                    $push: {
                        inventory: {
                            name: item.name,
                            amount,
                            category: item.category
                        }
                    }
                } , {
                    upsert: true,
            });
        } else {
            await client.database.user.findOneAndUpdate(
                {
                    userID: user.id,
                }, {
                    userID: user.id,
                    $pull: {
                        inventory: {
                            name: item.name
                        }
                    } 
                } , {
                    upsert: true,
            });
                
            await client.database.user.findOneAndUpdate(
                {
                    userID: user.id,
                }, {
                    userID: user.id,
                    $push: {
                       inventory: {
                            name: item.name,
                            amount: item.amount + amount,
                            category: item.category
                        }
                    }
                } , {
            upsert: true,
        });
    }
    return { name: item.name, amount, category: item.category };
}

module.exports.dropItem = async (client, user, category, interaction) => {
    if(!client instanceof Client) throw new Error("Client is not an instance of Discord.js Client");
    if(!user instanceof User) throw new Error("User is not an instance of Discord.js User");
    if(!category) throw new Error("Category is not defined");
    if(typeof category !== "string") throw new Error("Category is not a string");

    let droppedItems = [];
    
    for (const item of client.items) {
        for(let i = 0; i < client.items.length; i++) {
            if(!client.items[i].category === category) return;
        }

        const dropAmount = Math.floor((Math.random() * 3) + 1);
        const dropChance = Math.floor(Math.random() * 100);
        if(dropChance > item.dropChance) return;

        const itemDropped = await this.addItem(client, user, item, dropAmount, interaction)
        console.log(itemDropped); // This logs the item correctly

        droppedItems.push(itemDropped);
    }

    return droppedItems; // This always returns "undefined"
}

Expected result: An array with objects, each object containing a name, amount and category value;

Actual result: Console-logging the array returns “undefined”

I have tried awaiting the push, making the array a constant and more small things like that.
Could it be because the array isn’t in the loop?

same values on dropdown menu using v-for

I’m just starting using Vue.js to do a points counter app and I’m having troubles with v-for loop and dropdown menu.

I have an array of players in my Vue.js app :

var app = new Vue({
    el: '#leaderboard',
    data: {
        players: [{'name': 'Quentin', 'points': 0}, {'name': 'Kevin', 'points': 0}]
    },
    computed: {
        orderPlayers: function(){
            const compare = (a, b) => {
                return a.points - b.points;
            }
            console.log(this.players.sort(compare).reverse());
            return this.players.sort(compare).reverse();
        }
    }
})

And I am trying to display my elements in a div sorted by number of points like this :

    <div id="leaderboard-wrapper">
        <span>Classement :</span>
        <div id="leaderboard">
            <div v-for="(player, index) in orderPlayers" :key="index" class="element">
                <span id="name">{{ player.name }}</span>
                <span id="points">{{ player.points }}<i class="fa-solid fa-star"></i></span>
                <div class="dropdown">
                    <button class="dropbtn" onclick="showDropdown()"><i class="fa-solid fa-ellipsis-vertical"></i></button>
                    <div id="actionDropdown" class="dropdown-content">
                        <a href="#" @click="player.points+=2">A marqué 2</a>
                        <a href="#" @click="player.points +=5">A marqué 5</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

The problem is when I hit the button “A marqué 2” for Kevin, it is the points counter of Quentin that increment.

I made some tests and researches and I discover that the “player” value in the #actionDropdown div is the same for the two players. Here, player points on the player Quentin for the two elements.

Did someone have an idea to fix this problem ?

Thank you in advance ! 🙂

backfilling a DB with async await inside of a while loop JS

I have a function triggered onClick from my client which is supposed to back fill a separate DB with the first 100 items from the api.

seedDb()

  async function seedDb() {
    let i = 0;
    let offset = 0;

    while (i <= 100) {
      console.log(i);

      const { data } = await axios.get(
        `https://someapi?limit=20&offset=${offset}`
      );

      await axios.post("http://localhost:3001/marvel", data);

      offset = i;
      i += 20;
    }
  }

this is the functionality of the /marvel endpoint

export const backFill = async (req, res) => {
  const { data } = req.body;
  formatAndSaveData(data.results)

}

const formatAndSaveData = async (array) => {
  const marvelChars = array.map((res) => {
    return {
      name: res.name,
      description: res.description,
      marvelId: res.id
    }
  })

  await prisma.Character.createMany({
    data: marvelChars
  })
  console.log('Success')
}

The problem I’m having is the axios.post req is stopping the loop from executing again. In the logs I see i logs once as 0 Is there any work around for this?

How to return the number of HTML list elements on change using an event listener in JavaScript?

My todo list appends every input value starting with the number of elements in the list. So, entering the first item “Do homework” outputs to “1. Do homework.” And the second input “Learn JS” outputs to “2. Learn JS.” However, when deleting an element in the middle of the list, the number adjacent to the item doesn’t adjust accordingly to the number of current list elements.

For example, if the output is:

1. Do homework
2. Learn JS
3. Practice piano

Deleting number 2 will return:

1. Do homework
3. Practice piano

Instead of the correct output:

1. Do homework
2. Practice piano

var listset = document.querySelector('#add').addEventListener('click', newItem);


function newItem() {


  var lilist = document.getElementById("listForm").getElementsByTagName("li")
  var largo = lilist.length + 1
  var node = document.createElement('li');
  var inputValue = document.getElementById('input').value

  const delButton = document.createElement('img')
  delButton.src = "https://www.upload.ee/image/14249875/delete-button.jpg"
  delButton.width = 15;
  delButton.height = 15;



 delButton.addEventListener('click', function(e){
    e.target.closest('li').remove()
  })

  
 

  var textNode = document.createTextNode(largo +'. '+ inputValue + " ");

  node.appendChild(textNode)


  if (inputValue !== '') {
    var item = document.getElementById('listForm').appendChild(node);
    item.appendChild(delButton)
    document.getElementById('input').value = '';
  }


 



}
h1 {
    font-family: 'Courier New', Courier, monospace;
    font-size: 35px;
    text-align: center;
}

.header2 {
  font-family: Arial, Helvetica, sans-serif;
  text-align: center;
  font-size: 18px;
}



.main-page {
  margin-top: 150px;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
}


ul {
    list-style-type: none;
    margin-top: 150px;
    margin-left: 50px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 18px;
}

li {
    margin-top: 10px;
}



.list {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 18px;
  margin-left: 100px;
  padding: 10px 10px;
  width: 40%;
  margin-bottom: -151px;
}


#input {
    font-size: 18px;
}

#add {
    background-color: rgb(233, 235, 235);
    font-size: 18px;
    margin-left: -3px;
}


#listForm {
    color: black;
    margin-left: 100px;
    width: 284px;

}

li {
    margin-bottom: -5px;
}

li:hover {
    cursor: grab;
    color: rgb(176, 171, 171)

}


#listForm .checked {
    text-decoration: line-through;
}

.unchecked {
    text-decoration: none;
}
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>To Do List: Raamis Ali</title>
    <meta name="description" content="A todo list application">
    <meta name="author" content="Raamis Ali">
    <link rel="stylesheet" href="list.css"> </head>

<body>
    <script src="javascript.js"></script>
    <div class="main-page">
        <h1>To Do List Web App</h1>
        <p class="header2">Created by Raamis Ali</p>
        <div class="list">
            <input type="text" id="input" placeholder="Add items">
            <input type="button" value="Add" id="add" onclick="newItem()"> </div>
        <ul id="listForm"> 
      </ul>
        <br> </div>
</body>

</html>

I have tried implementing this event listener and function with different variations of this but I have had no success:

largo.addEventListener('change', updateValue())
function updateValue(e) {
var lilist = document.getElementById("listForm").getElementsByTagName("li")
lilist.length + 1 == e.target.value;
}

Having an issues with Hacker rank question : Caesar Cipher

I have a solution that gives the correct intended output, but it still only passes 7/12 tests.

Below is an example of one that shows as incorrect, but when I compare vs the intended output vs mine it the exact same (I copied into VS code and highlight and both match) :

function caesarCipher(s, k) {
  let splitString = s.split("")
  console.log(splitString);
  let charCodeArray = []
  let moveFactor = k % 26

  for (let i = 0; i < splitString.length; i++) {
    let char = s.charCodeAt(i)
    if (char > 64 && char < 91) {
      if ((char + moveFactor) > 90) {
        charCodeArray.push((char + moveFactor) - 26)
      } else {
        charCodeArray.push(char + moveFactor)
      }
    } else if (char > 96 && char < 123) {
      if ((char + moveFactor) > 122) {
        charCodeArray.push((char + moveFactor) - 26)
      } else {
        charCodeArray.push(char + moveFactor)
      }
    } else {
      charCodeArray.push(char)
    }
  }
  console.log(charCodeArray)
  let charCodeModified = String.fromCharCode.apply(null, charCodeArray)
  return charCodeModified
}
console.log(caesarCipher("6DWV95HzxTCHP85dvv3NY2crzt1aO8j6g2zSDvFUiJj6XWDlZvNNr", 87))

how to update in nested array in MongoDB

I’m trying to update seat_status but i’m new to Mongodb I try to use aggregate function but it’s not modifying original document then I try $ operator but not worked as i expected this is my collection…………………………………………………………………………………………………………………………………………………………………

{
    "_id": {
        "$oid": "62b0c3342f155a7ad94cc81c"
    },
    "totalShowByDay": "2",
    "totalShowDays": 4,
    "movieId": {
        "$oid": "62b04c782828dd04f0d1c1ad"
    },
    "screenId": {
        "$oid": "62b04b8e2828dd04f0d1c1ac"
    },
    "createdAt": 1655751476553,
    "showId": {
        "$oid": "62b0c3342f155a7ad94cc6db"
    },
    "show_seats": [{
        "showByDate": {
            "ShowDate": "2022-06-20",
            "shows": [{
                "showTime": "2022-06-20T10:00",
                "showSeats": [{
                    "_id": {
                        "$oid": "62b0c3342f155a7ad94cc6dc"
                    },
                    "seat_number": "1",
                    "tag_name": "A",
                    "seat_status": false,
                    "user_id": false,
                    "price": "110",
                    "seats_category": "CLASSIC",
                    "show_time": "2022-06-20T10:00"
                }, {
                    "_id": {
                        "$oid": "62b0c3342f155a7ad94cc6dd"
                    },
                    "seat_number": "2",
                    "tag_name": "A",
                    "seat_status": false,
                    "user_id": false,
                    "price": "110",
                    "seats_category": "CLASSIC",
                    "show_time": "2022-06-20T10:00"

this is the code i try to modify……………………………………………………………………………………………………………………………………

 db.seats.updateOne({"show_seats.$.showByDate.shows.$.showSeats.$._id:ObjectId("62b0c3342f155a7ad94cc81c")},{$set:{"show_seats.$.showByDate.shows.$.showSeats.$.seat_status":1}})

how get data form json from ajax ? to javascript

with ajax json data : {“data”:[{“product_price”:”3000″}]}

how call data :3000 from data and product price

$.ajax({
            type: "POST",
            dataType: 'html',
            url: '<?php echo base_url() . "index.php/product/getdataJson/" ?>' + product_id,
            data: {
                'product_id': product_id
            },
            success: function(data) {

                var data_json = JSON.parse(data);  // dont work

                document.getElementById("demo").innerHTML = data_json.data ; // dont work

      },
            error: function() {
                alert("did not work");
            }

        });





<p id="demo"></p>

How to loop and display MySQL dates into FullCalendar

I am using python with bottle framework and JavaScript, and I want to display fetched MySQL dates into FullCalender. I am successfully fetching the data from MySQL, as shown below, but the problem is when I pass the value “dates” to the “start” key, my expectation was to see all the dates in the Callendar, but instead, I am only getting the last date.

Here is my JavaScript code:

<script>
    let calendarElement = document.querySelector("#calendar");
    fetch('/api-fetch-booking_data')
    .then(res => res.json())
    .then(data => {
        data.booking_dates.forEach(element => {
            let dates = element.avalable_dates
            console.log(dates);                
            let calendar = new FullCalendar.Calendar(calendarElement, {
                
                events: [
                    {
                        start: dates,
                    }
                ]
            
            });
        calendar.render();
        })
    })
</script>

These are the dates fetched from MySQL:

enter image description here

This is the UI, as you can see I am only getting the “2022-06-30” date:

enter image description here

I have saw that you could do a forloop like this using flask:
enter image description here

but I really don’t know how and even if it is bossible to do it with bottle. Hope someone will help me up with this. Thanks in advance.

Double tap redirect only working for the first row on loop

I’m still new to JavaScript and I am try to achieve a double click feature.

The visitor double click on the video and redirect to the page with a unique Id attach to the url but i can’t get it working. Here’s my code

This only redirect for the first video but not working for other

        <video id="doubleTap" autoplay muted>  
    <input id="id" value="1">
    <source src="/ver/videos/2024.mp4" type="video/mp4">
    </video>
    
            <video id="doubleTap" autoplay muted>  
    <input id="id" value="2"> 
          <source src="/ver/videos/2023.mp4" type="video/mp4">

    </video> 
            
<video id="doubleTap" autoplay muted>
            <input id="id" value="3">              
 <source src="/ver/videos/2022.mp4" type="video/mp4">


    </video>
                <script type="text/javascript">
        
        $("#doubleTap").doubleTap(function() {
            var id = document.getElementById("id").value;
        location.href='h.php?id='+id;
        });
        
    </script>

how to set an array of data source with useState?

Im trying to set an array that I called it from data base with useState but when i call the new array is empty. why?
here I set “alumnos” from the database in array, here i have the name, lastname1, lastname2

const [alumnos, setAlumnos] = useState([]);
  
  const cargarAlumnos = async () => {
  const response = await fetch("http://localhost:4000/alumno")
  const data = await response.json();
  setAlumnos(data);
}

useEffect(() => {
  cargarAlumnos();
}, []);

then i want to set default some values here:

const data = [];
for (let i = 0; i < alumnos.length; i++) {
  data.push({
    key: alumnos[i].id_alumno,
    Nombre: alumnos[i].nombre_alumno,
    ApellidoPaterno: alumnos[i].apellidop_alumno,
    ApellidoMaterno: alumnos[i].apellidom_alumno,
    criterio1: 0,
    criterio2: 0,
    criterio3: 0,
    criterio4: 0,
    criterio5: 0,
    puntaje: 0,
    nota: 1.0
  });
}

data is correct i have an array with this information:

(56) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
ApellidoMaterno: "Bignal"
ApellidoPaterno: "Van Eeden"
Nombre: "Franzen"
criterio1: 0
criterio2: 0
criterio3: 0
criterio4: 0
criterio5: 0
key: 1
nota: 1
puntaje: 0

this values i push into a array data and finally i want to setDatasource here:

 const [dataSource, setDataSource] = useState(data);

but dataSource still an empty array, why??

can JavaScript switch-case statement be used to update its own argument?

I’m trying to experiment with a small lightbulb switch JavaScript challenge(from w3schools). I already tried with if statement to see if I can change the bulb from off to on and vice versa with a single button, and it worked. Now I’m trying to do the same with the switch-case statement, but it doesn’t work.

This is what the code looks like:

<!DOCTYPE html>
<html>
<body>



<button onclick="lightswitch(sw)">Light Switch</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">



<script>

var sw = 0;
function lightswitch(sw){

  switch(sw){
    case 1: 
    document.getElementById('myImage').src='pic_bulboff.gif'
    sw=0;
    break;

    case 0:
    document.getElementById('myImage').src='pic_bulbon.gif'
    sw=1;
    break;
   }
}
</script>

</body>
</html>

I checked with console log and the ‘sw’ variable does not get updated from the switch case and keeps retaining its original value outside the lightswitch function. Is there any specific reason why this happen? and can I work around it?