How to remove all tags between two tags using Javascript (not Jquery)?

This is how certain external css files are placed between two meta tags.

<meta id="front-template-css-anchor-start" name="front-template-css-anchor-start" content="This is where front template css will be added"/>
    <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/bootstrap.min.css" />
    <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/LineIcons.2.0.css" />
    <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/animate.css" />
    <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/tiny-slider.css" />
    <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/glightbox.min.css" />
    <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/main.css" />
<meta id="front-template-css-anchor-end" name="front-template-css-anchor-end" content="This is where front template css will be added"/>

In my js code, I tried to get the two meta tags like this:-

var frontTemplateCssAnchorStart       = document.querySelector('#front-template-css-anchor-start');
var frontTemplateCssAnchorEnd         = document.querySelector('#front-template-css-anchor-end');

I want to iterate from frontTemplateCssAnchorStart to frontTemplateCssAnchorEnd and delete/remove all <link> tags. But I am stuck and don’t know how to proceed from here. Maybe siblings() function can work, but I am not sure. sibling() can work among children of a parent node, but here the links aren’t child of the mentioned tags.

How can I solve this?

How to get “BoundingClientRect” of a flex box’s row?

I have made a simple text reader with “flow” mode and “flip” mode.

flow mode use browser’s default scrollbar to scroll down texts.

flip mode use flex-wrap: wrap; to devide text into pages,

and translate: calc((-100% - var(--padding) * 2) * var(--page)) to flip.

But now I got some problems:

If elements inside is longer then it’s flex box container, there will be some content that will never be able to see.

If elements inside is wider then container, it will squeeze other content and cause the offset to be in an incorrect position.

But The container’s size is dynamic. Only with data from getBoundingClientRect is not enough to fix those problem.

Do I need to find another approach? Or is there any way to get inner box data of flex box?

ERROR:crashpad_client_win.cc(867)] not connected – Electron js

Basically I’m calling a c++ function through addon into my Electron js javascript code. I have to use this function in a interval every 1 second. The function works fine however sometimes the app crashes with this message.

ERROR:crashpad_client_win.cc(867)] not connected

i am calling function like this,

const addon = require("addon.node");

addon.getOperaURL()

please suggest me solution to get rid of this crash completely.

I don’t know if it is related but to facilitate further here is my c++ function

std::wstring getOperaURL(HWND windowHandle) {
    // Checking if the address bar for the given window handle is already cached
    for (const auto& cachedAddressBar : cachedAddressBars) {
        if (IsWindow(cachedAddressBar.windowHandle) && IsWindow(windowHandle) &&
            (cachedAddressBar.windowHandle == windowHandle)) {
            std::wstring cachedUrl = retrieveUrlFromAddressBar(cachedAddressBar.addressBarElement);
            return cachedUrl;
        }
    }

    HRESULT hr = CoInitialize(nullptr);
    if (FAILED(hr)) {
        return L"Error initializing COM";
    }

    // Initialize pointers to nullptr for proper resource management
    IUIAutomation* automation = nullptr;
    IUIAutomationElement* desktop = nullptr;
    IUIAutomationElement* operaWindow = nullptr;
    IUIAutomationElement* addressBar = nullptr;
    IUIAutomationCondition* addressBarCondition = nullptr;
    IUIAutomationCondition* editControlCondition = nullptr;
    IUIAutomationCondition* titleCondition = nullptr;

    do {
        // Create UI Automation instance
        hr = CoCreateInstance(CLSID_CUIAutomation, nullptr, CLSCTX_INPROC_SERVER, IID_IUIAutomation, (void**)&automation);
        if (FAILED(hr)) {
            break;
        }

        // Get the desktop element
        hr = automation->GetRootElement(&desktop);
        if (FAILED(hr)) {
            break;
        }

        // Find the Opera window using "Pane" as the control type
        hr = automation->CreatePropertyCondition(UIA_NativeWindowHandlePropertyId, CComVariant(reinterpret_cast<LONG>(windowHandle)), &addressBarCondition);
        if (FAILED(hr)) {
            break;
        }

        hr = desktop->FindFirst(TreeScope_Descendants, addressBarCondition, &operaWindow);
        if (FAILED(hr)) {
            break;
        }

        // Find the address bar using "Edit" as the control type
        hr = automation->CreatePropertyCondition(UIA_NamePropertyId, CComVariant(L"Address field"), &titleCondition);
        if (FAILED(hr)) {
            break;
        }
        hr = automation->CreatePropertyCondition(UIA_ControlTypePropertyId, CComVariant(UIA_EditControlTypeId), &editControlCondition);
        if (FAILED(hr)) {
            break;
        }
        hr = automation->CreateAndCondition(titleCondition, editControlCondition, &addressBarCondition);
        if (FAILED(hr)) {
            break;
        }
        // Find the address bar using the combined condition
        hr = operaWindow->FindFirst(TreeScope_Subtree, addressBarCondition, &addressBar);
        if (FAILED(hr)) {
            break;
        }
        // Cache the address bar element along with the window handle
        // cachedAddressBars.emplace_back(addressBar, windowHandle);

        // Retrieve and return the URL
        VARIANT addressBarValue;
        hr = addressBar->GetCurrentPropertyValue(UIA_ValueValuePropertyId, &addressBarValue);
        if (FAILED(hr)) {
            break;
        }

        // Convert VARIANT to wstring
        std::wstring url(addressBarValue.bstrVal);
        VariantClear(&addressBarValue);

        return url;

    } while (false);

    // Cleanup resources in case of an error
    if (addressBarCondition) addressBarCondition->Release();
    if (editControlCondition) editControlCondition->Release();
    if (titleCondition) titleCondition->Release();
    if (addressBar) addressBar->Release();
    if (operaWindow) operaWindow->Release();
    if (desktop) desktop->Release();
    if (automation) automation->Release();

    CoUninitialize();
    return L"Error in UI Automation";
}

Saving data from a website to a text document

After filling out the form, all data should be written to a text document, but in it all data is written as undefined. How to solve this problem? (also the text is displayed incorrectly on the site when the data is successfully saved, I also don’t understand why)
form_scripts.js

document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('appointment-form');
    form.onsubmit = function (event) {
        event.preventDefault();
        const formData = new FormData(form);

        fetch('/submit-form', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                const resultElement = document.getElementById('result');
                resultElement.textContent = data.message;
                resultElement.style.color = 'green'; // Устанавливаем цвет текста
                form.reset(); // Очищаем форму после отправки
            })
            .catch(error => {
                console.error('Ошибка:', error);
                document.getElementById('result').textContent = 'Произошла ошибка при отправке формы.';
                document.getElementById('result').style.color = 'red'; // Устанавливаем цвет текста при ошибке
            });
    };
});

form.js

<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">
    <title>Форма записи в клинику</title>
</head>
<body>
    <!-- Header начало -->
    <header class="header">
        <div class="container">
            <a class="logo" href="clinic_index.html">Техномед</a>
            <nav class="nav">
                <a href="form.html">Сервис</a>
                <a href="#about">О нас</a>
                <a href="#contact">Контакты</a>
            </nav>
        </div>
    </header>
    <!-- Header конец -->

    <div class="container">
        <h1>Форма записи на прием</h1>
        <form action="/submit-form" method="post" id="appointment-form">
            <label for="fullname">ФИО:</label>
            <input type="text" id="fullname" name="fullname" required><br><br>

            <label for="phone">Номер телефона:</label>
            <input type="tel" id="phone" name="phone" required><br><br>

            <label for="address">Адрес:</label>
            <input type="text" id="address" name="address" required><br><br>

            <label for="service">Выберите услугу:</label>
            <select id="service" name="service">
                <option value="consultation">Консультация</option>
                <option value="treatment">Лечение</option>
                <option value="diagnostics">Диагностика</option>
                <!-- Другие услуги -->
            </select><br><br>

            <label for="symptoms">Симптомы:</label>
            <textarea id="symptoms" name="symptoms"></textarea><br><br>

            <input type="submit" value="Отправить">
        </form>
        <div id="result"></div>
    </div>

    <script src="form_script.js"></script>
</body>
</html>

server.js

const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const port = 1338; // Вы можете выбрать любой доступный порт

// Подключаем встроенный парсер для данных формы
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static(__dirname + '/public'));
// Устанавливаем путь к вашим HTML-файлам в папке public
app.post('/submit-form', (req, res) => {
    const { fullname, phone, address, service, symptoms } = req.body;
    const dataToSave = `${fullname}t${phone}t${address}t${service}t${symptoms}n`;

    // Путь к файлу, где будут сохраняться данные
    const submissionsDir = path.join(__dirname, 'submissions');
    const filePath = path.join(submissionsDir, 'submissions.txt');

    // Создаем папку 'submissions', если она не существует
    if (!fs.existsSync(submissionsDir)) {
        fs.mkdirSync(submissionsDir);
    }

    // Добавляем данные в файл
    fs.appendFile(filePath, dataToSave, 'utf8', (err) => {
        if (err) {
            console.error('Ошибка при сохранении данных:', err);
            res.status(500).setHeader('Content-Type', 'application/json; charset=utf-8');
            res.json({ message: 'Произошла ошибка сервера' });
        } else {
            res.setHeader('Content-Type', 'application/json; charset=utf-8');
            res.json({ message: 'Ваши данные успешно переданы клинике.' });
        }
    });
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

I tried to write these functions for the correct text but it didn’t help

res.status(500).setHeader('Content-Type', 'application/json; charset=utf-8');

Why is this not doing the same thing? [closed]

If i delete this line:

tasksContainer.innerHTML = "";

… and change += into = in the 5th line, the code is not doing the same thing. Why?

I expected those two things to do the same. Even when I check with console.log() it looks like its doing the same but its not showing it on the screen.

const updateTaskContainer = () => {
  tasksContainer.innerHTML = "";

  taskData.forEach(
    ({ id, title, date, description }) => {
        (tasksContainer.innerHTML += `
        <div class="task" id="${id}">
          <p><strong>Title:</strong> ${title}</p>
          <p><strong>Date:</strong> ${date}</p>
          <p><strong>Description:</strong> ${description}</p>
          <button type="button" class="btn">Edit</button>
          <button type="button" class="btn">Delete</button> 
        </div>
      `)
    }
  );
};

Await across different files – Javascript

I’ve done a bit of research about promises, the event loop, and async. Naturally, I came across await. From what I understand, it’s used in async functions in order to pause the completion of a promise, waiting for previous promises in the queue to be completed. What I was curious about was if await also works across different files. For example, in the backend of a website, I’m making. From this post: Getting error “Converting circular structure to JSON” while working with express,mongodb

It said that we need to include await for our models in the async function, but wasn’t if it was because of awaits across multiple files or something else.

I’m trying to delegate events (“click”) to apply my function to dynamically created cards with vanilla Java Script

I’m trying to apply a feature that hides or shows the back of dynamically created cards when clicked (and vice versa). The first function worked, but it only applied to the template, so I found that the way to solve it was to delegate the event to an element that was already present in the HTML.

This is the feature I’ve been working on

let isFlipped = false;

const mainContainer = document.getElementById("root");
mainContainer.addEventListener('click', function(){
  if(event.target.matches('.button-container')) {
    const card=event.target.closest('.card-container');
    turnCard(card);
    if (event.target.matches('.back')) {
      const card=event.target.closest('.card-container');
      returnCard(card); 
    }
  }
})
function turnCard(card) {
  const frontCard=document.querySelector("#front-card");
  const backCard=document.querySelector("#back-card");

  if (isFlipped) {
    backCard.classList.toggle('hide');
    frontCard.classList.toggle('hide');
  }
  isFlipped = !isFlipped;
} 
function returnCard (card){
  const frontCard=document.querySelector("#front-card");
  const backCard=document.querySelector("#back-card");

  if(!isFlipped){
    backCard.classList.toggle('hide');
    frontCard.classList.toggle('hide');
    isFlipped = !isFlipped;
  }
}

and this is the cards structure

 data.forEach(element => {
    const cardItem = document.createElement('li');

    cardItem.innerHTML += `<li class="card-container" itemscope itemtype="https://schema.org">
    <article id="front-card">
      <h2>${element.name}</h2>
      <div class="top-card">
        <img alt="Plant Name" src="${element.imageUrl}">
        <dl itemscope itemtype="https://schema.org" class="facts">
          <div class="amounts">
            <dt itemprop="water-amount" class="amount">Water</dt>
              <dd>
                <img alt="Gota" src="resources/Icons/agua-activa.png" >
                <img alt="Gota" src="resources/Icons/agua-activa.png" >
                <img alt="Gota" src="resources/Icons/agua-inactiva.png" class="inactiva">
              </dd>
          </div>
          <div class="amounts">
            <dt itemprop="light-amount" class="amount">Light</dt>
              <dd>
                <img alt="Sol" src="resources/Icons/luz-activa.png" >
                <img alt="Sol" src="resources/Icons/luz-inactiva.png" class="inactiva" >
                <img alt="Sol" src="resources/Icons/luz-inactiva.png" class="inactiva" >
              </dd>
          </div>
          <div class="amounts">
            <dt itemprop="care-amount" class="amount">Care</dt>
              <dd>
                <img alt="Semaforo" src="resources/Icons/cuidado-activa.png" >
                <img alt="Semaforo" src="resources/Icons/cuidado-inactiva.png" class="inactiva" >
                <img alt="Semaforo" src="resources/Icons/cuidado-inactiva.png" class="inactiva" >
              </dd>
          </div>
        </dl>
      </div>
      <p>${element.shortDescription}</p>
      <div class="button-container">
        <button>Detalles</button>
      </div>
    </article>
    <article id="back-card" class="hide">
      <h2>${element.name}</h2>
      <div class="top-card">
        <img alt="Plant Name" src="${element.imageUrl}">
        <dl itemscope itemtype="https://schema.org">
          <dt class="scientific">${element.scientificName}</dt>
          <dt class="detail">Botanical Family</dt><dd>${element.botanicalFamily}</dd>
          <dt class="detail">Usage</dt><dd>${element.applications}</dd>
          
        </dl>
      </div>
      <div class="bottom-card">
        <dl id="description">
        <dt>Climate data</dt><dd>${element.climaticData}</dd>
          <dt>Description</dt><dd>${element.description}</dd>
          <dt>Maintenance</dt><dd>${element.maintenance}</dd>
        </dl>
        <div id="icons">
          <div class="stats">
            <img class="stats1" alt="Estadisticas 1" src="resources/Icons/estadisticas-1.png">
            <img class="stats2" alt="Estadisticas 1" src="resources/Icons/estadisticas-2.png">
          </div>
          <div class="back">
            <img alt="Regresar" src="resources/Icons/Regresar.png">
          </div>
        </div>
      </div>
    </article>
  </li>`

    cardList.appendChild(cardItem);

  });
  
  return cardList;
};

Data from Angular Service is not provided in template after passing from service

After creating an API Backend with Django i tried to get an Angular Component to display the data provided to create a list of all fetched datasets.

I was able to get an test in service.spec.ts running and i got validated that the data is correctly fetched from the backend

I am struggling a bit with angular v.17 syntax so maybe the problem is quite simple.

Here is the code:

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ProjectDashboardService } from './project-dashboard.service' ; // Updated import path
import { Project } from './project.model'; // Updated import path

@Component({
  selector: 'app-project-dashboard',
  standalone: true,
  imports: [CommonModule],
  //templateUrl: './project-dashboard.component.html',
  template:` 
          <div class="container">
            <div class="row">
              <div class="col-md-12">
                <div class="card">
                  <h5 class="card-header">Projekte</h5>
                  <div class="card-body">
                    <div class="table-responsive">
                      <table class="table table-striped table-hover">
                        <thead>
                          <tr>
                            <th>Projektname</th>
                            <th>Beschreibung</th>
                            <th>Level</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr>
                            <ng-template ngFor let-project [ngForOf]="projects">
                              <td>{{project.project_name}}</td>
                              <td>{{project.project_description}}</td>
                              <td>{{project.project_level}}</td>
                            </ng-template>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </div>  
            </div>
            `,
  styleUrl: './project-dashboard.component.scss',
  providers: [ProjectDashboardService] // Updated provider
})


export class ProjectDashboardComponent implements OnInit {
  projects!: Project[]; // Updated type
  projectDashboardService: ProjectDashboardService; // Declare projectDashboardService property

  constructor(projectDashboardService: ProjectDashboardService) {
    this.projectDashboardService = projectDashboardService; // Assign projectDashboardService in the constructor
  }

  ngOnInit() {
    this.projectDashboardService.getProjectDashboardList()
      .subscribe(projects => this.projects = projects);
  }
}

in the end i would like to get an responsive page that shows all current projects fetched

Password login show Div localstorage

Is there any way to make localstorage work to always show the contents of the “Lorem ipsum” div, when login is successful?

This way, when someone enters the password correctly, the content would always be visible, and stored with localstorage, and if it is also possible to hide the password field and the login button…

what I have achieved so far:

    jsfiddle.net/thvinic/697bcq2t/1

password in the exemple is 12345

help me please!
Thank you for any help!

Next JS 13/14 – Server component not refetching data when revisited (Without refreshing)

When trying to fetch the latest like items from a server component in next, thats the only data that will show until I manually refresh the page. When navigating away and returning, I want the data to be refetched but it doesn’t – when using an anchor tag over Link it works

export default async function DjProfile({ params }) {
  const tracks = await getUserLikes(params?.id);

  return (
    <Suspense fallback={<LoadingGrid />}>
      <TrackContainer tracks={tracks} />
    </Suspense>
  );
}
const getUserLikes = async (userId) => {
  const likesRef = collection(db, "likes");
  const querys = query(likesRef, where("currentUser", "==", userId));
  const querySnapshot = await getDocs(querys);

  const likesData = [];

  querySnapshot.forEach((doc) => {
    const data = doc.data();
    likesData.push(data);
  });


  console.log("new likes", likesData);

  return likesData;
};

Unsure how to handle this, as I am using Firestore and not next fetch which has some caching things I could add

When ‘use client’ is used with useEffect works fine, but for performance isnt server components better – as I don’t need a live update on the actual page, just when a user navigates to it

How to detect when you can’t go back any further in the navigation stack in React-router-dom useNavigate()? [duplicate]

I implemented a “back” button which sets navigate(-1), where navigate is declared with const navigate = useNavigate(). I am using react-router-dom: v6.21.0 with reactstrap.

I can successfully go back but I want to detect if I can no longer go back (empty navigation stack) and disable this button. How would I do that check?

I tried looking into useLocation() and the pathname parameter with the homepage (pathname: '/'), but it doesn’t work because a user may go between pages and the homepage at some point and the back button should allow them to go all the way back. Instead, by using the pathname, it shortcuts the back button preventing a user from going back when there is supposedly more pages left on the navigation stack.

Thanks for the help.

Safari 17.2 (macos) audio src not loading when set to object url

I have Safari 17, macos. I am trying to set the src of an audio tag like <audio src="blob:...">

    // 'data' is set to a data url, e.g. data:audio/mp3;base64,SUQzBAAA etc
    const audio = document.querySelector('audio');
    const spl = data.split(',');
    const binary = atob(spl[1]);
    const mime = spl[0].split(':')[0].split(';')[0];
    let ar = []; for (let i=0; i<binary.length; i++) { ar.push(binary.charCodeAt(i)); }
    blob = new Blob([new Uint8Array(ar)],{type: mime});
    audio.src = URL.createObjectURL(blob);

In Firefox & Chromium-based browsers this all works fine. Safari gives me the word Error on the audio control, the error Uncaught (in promise) DOMException: The media resource indicated by the src attribute or assigned media provider object was not suitable. on the console, and refuses to play.

I understand that browsers can just handle having the data url as the src but I would prefer the blob reference rather than a string copy in the src, as the contents can be quite large.

The audio tag is just <audio controls>; it adds the blob src attribute. I’ve also tried explitly adding the type='audio/mp3' or type='audio/mpeg' attributes as well, but these do not change the message or error. Safari just seems unable to play object urls.

Does anybody know what the definition of not suitable is in the errors context?

Video from Google Drive folder doesn’t display properly in JavaScript + HTML code

I have the following situation:

I have a public shared link in a google drive folder (also public) for an mp4 video that I’d like to display in a web page.

Here’s the JS code:

var creativelink = "https://drive.google.com/file/d/MY_FILE_ID/view?usp=sharing";

console.log("creativelink : "+creativelink);

// Regular expression to extract the file ID
var imagelink = creativelink.match(//file/d/([^/]+)/)[1];
console.log("imagelink : " + imagelink);

  creativeImage = '<video controls width="340" height="auto"><source src="https://drive.google.com/uc&id=' + imagelink + '" type="video/mp4"></video>';

console.log("creativeImage : " + creativeImage);
document.getElementById('creative').innerHTML = creativeImage;

And here’s the HTML code:

<div id="creative" class="text-center"></div>

This same code used to work fine before. For some reason it’s not working anymore.

The video is not displayed as expected, as you can see in the following screenshot:

enter image description here

There is no video, only this static image that cannot be played.

I also tried changing the code as you can see below:

creativeImage = '<video controls width="340" height="auto"><source src="https://drive.google.com/uc?export=download&id=' + imagelink + '" type="video/mp4"></video>';

The result expected was the video to be played, however I have the same result as before.

I couldn’t find a reasonable explanation neither a solution for this issue.

Thank you in advance!