Move next sibling element into previous sibling

I have a poorly formatted sidebar (aside) which I have no control over the structure.

But I want to make it the correct html structure by moving the elements which are supposed to be children into their parent elements.

I want to end up with something that is html valid:

<aside class="sidebar">
 <div class="sidebar-nav">
  <ul>
  <li><a>Title 1</a>
   <ul>
    <li><a>Title 2</a>
    <ul>
     <li><a>Title 3</a>
     ...
     ...
  </ul>
 </div>
</aside>

At the moment this is the html structure I’m working with, and the javascript I’ve got to. I realise at this point the looping of the function is causing it to recursively append the next element into the previous.

However, this means that I end up with so many more iterations.

// -- get the sidebar list
const sidebarList = document.querySelector('div.sidebar-nav > ul');

const reorder = ((list) => {
    const listItems = list.querySelectorAll(':scope li');
    listItems.forEach((element) => {

    // -- last h6 wont have a next sibling
    if (element.nextElementSibling === null) return;

    // -- if it is a second sub heading skip
    if (element.nextElementSibling.tagName !== 'UL') return;

    // -- add into the next element
    element.innerHTML = element.innerHTML + element.nextElementSibling.innerHTML
    });
})(sidebarList);
<aside class="sidebar">
  <div class="sidebar-nav">
    <ul>
      <li><a>Heading level 1</a></li>
      <ul>
        <li><a>Heading level 2</a></li>
        <ul>
          <li><a>Heading level 3</a></li>
          <ul>
            <li><a>Heading Level 4 - 1</a></li>
            <li><a>Heading Level 4 - 2</a></li>
            <ul>
              <li><a>Heading Level 5</a></li>
              <ul>
                <li><a>Heading level 6</a></li>
              </ul>
            </ul>
          </ul>
        </ul>
      </ul>
      <li><a>Heading level 1</a></li>
      <ul>
        <li><a>Heading level 2</a></li>
        <ul>
          <li><a>Heading level 3</a></li>
          <ul>
            <li><a>Heading Level 4 - 1</a></li>
            <li><a>Heading Level 4 - 2</a></li>
            <ul>
              <li><a>Heading Level 5</a></li>
              <ul>
                <li><a>Heading level 6</a></li>
              </ul>
            </ul>
          </ul>
        </ul>
      </ul>
    </ul>
  </div>
</aside>

trying to adjust a state object in redux but i can’t change the value of one property in the object

Ok so i have this very basic example of redux state

const initialState = {
  good: 0,
  ok: 0,
  bad: 0,
};

const counterReducer = (state = initialState, action) => {
  console.log(action);
  console.log(state);
  console.log(initialState);
  console.log(state.good);

  switch (action.type) {
    case "GOOD":
      return { ...state, good: good + 1 };
    case "OK":
      return { ...state, ok: ok + 1 };
    case "BAD":
      return { ...state, bad: bad + 1 };

    case "ZERO":
      return state;
    default:
      return state;
  }
};

export default counterReducer;

i’m trying to change only one property of the state object on an onclick function named like this

const store = createStore(reducer);

const App = () => {
  const addGood = () => {
    store.dispatch({
      type: "GOOD",
    });
  };
  const addBad = () => {
    store.dispatch({ type: "BAD" });
  };
  const addOk = () => {
    store.dispatch({ type: "OK" });
  };

  return (
    <div>
      <button onClick={addGood}>good</button>
      <button onClick={addOk}>ok</button>
      <button onClick={addBad}>bad</button>
      <button>reset stats</button>
      <div>good {store.getState().good}</div>
      <div>ok {store.getState().ok}</div>
      <div>bad{store.getState().bad}</div>
    </div>
  );
};

const renderApp = () => {
  ReactDOM.render(<App />, document.getElementById("root"));
};

renderApp();
store.subscribe(renderApp);

but when i try to change the value of any of the properties it doesn’t work , for example good , ok , bad but it crashes my app if i do so with good is not defined error

How to link JavaScript and HTML5 pages without tag?

I am trying to make a button for my webpage that changes the ENTIRE colour palette of the page with Code.org AppLab. The only problem is, code.org doesn’t allow the use of the <script> tag for “security reasons”. As far as I know the only way I can turn on CSS settings with a button is with getElementById(). If anyone knows how to activate CSS settings when a button is clicked without JS, how to link external JS files to an html file, or use inline JS all WITHOUT the use of the <script> tag please show me how. Any help would be greatly appreciated.

I’m begging someone to help me PLEASE.

if statement with multiple or conditions returning wrong value

I am pretty sure I am missing something basic here but I am having trouble with using multiple or or || operators with my if statement.

For some reason the if statement is not catching the name variable:

testword = "billy"

if ((testword != "billy") ||
    (testword != "tom") ||
    (testword != "sara") ||
    (testword != "michael")) {
console.log("none of the names match")
} else {
console.log("name found!")
}

When I try this I get none of the names match when I should get name found!

How to extract the data behind the interactive map/figure

There is an interactive map on website like this:
https://www.bostonglobe.com/2021/12/15/nation/these-are-all-massachusetts-towns-that-have-indoor-mask-mandates/#bgmp-comments

Where when the mouse hovers on it, it will highlight that area and show info for that certain area. How to get the data behind these and exact all the data to excel etc.? Is it written in Javascript?

example figure

Cannot read .length property of undefined (sometimes)

I’m trying to get checkbox values as an array, so later I can use them as part of a GET request.

Checkboxes are like this:

<input type="checkbox" name="diet" value="gluten"/>
<input type="checkbox" name="diet" value="vegetarian"/>
<input type="checkbox" name="diet" value="vegan"/>

I’ve (almost) catch them with this:

function getCheckboxValues(form){
    var values= [];
    var diet = form.diet;

    for (let i = 0; i <diet.length; i++) {
        if (diet[i].checked) {
            values.push(diet[i].value);
        }
    }
    return values;
}

Then I want to get them into:

var reqDiet = []; //global

So I can merge it into my get params

document.getElementById("submit-btn").addEventListener("click", function (){
    reqParams = "&diet="+reqDiet+",
    getRecipe(ASK_RECIPE, reqParams)
})
async function getRecipe(reqRecipe, reqParameters){
    let response = await fetch(reqRecipe+API_KEY+reqParameters);
    recipe = await response.json();

    let recipeStored = JSON.stringify(recipe);
    sessionStorage.setItem("recipe",recipeStored);
};

The problem is, if i run the getCheckboxValues("form_id") in console, it returns the correct array with items, but if i do something like

reqDiet = getCheckboxValues("form_id");

Console says :

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘length’)
at getCheckboxValues

What I can understund from this is that my program is not recognizing “diet.length” as an array when I do the last one, but do recognize it when i run the function by itself.
I prefer to do this in vanilla JS since I’m new here and trying to do this small projects.

P.S. any feedback in the post is apreciated since is my first one and i think is pretty large :/ sorry about that

how to customize tsx syntax using babel?

I’m a newer to babel,I want to transform the code:

const posts = []

export const PostList = () => {
    const [fetchSignal, setFetchSignal] = useReducer(signal => !signal, false)
    const withRefresh = useWithRefreshScope()
    useEffect(() => {
        getArticles().then((res) => {
            withRefresh(
                () => {
                    posts.push(...res.data.articles)
                 
                }
            )
        })
    }, [fetchSignal])
    return (
        <>
     
        </>
    )
}

to this:

const posts = []
@useWithRefreshScope
export const PostList = () => {
    const [fetchSignal, setFetchSignal] = useReducer(signal => !signal, false)
    useEffect(() => {
        getArticles().then((res) => {
            withRefresh{
                    posts.push(...res.data.articles)
                }
        })
    }, [fetchSignal])
    return (
        <>
 
        </>
    )
}

I just want to create a scope syntax to reduce some boilerplate code,so that i need to write a babel plugin(maybe not?)
how can i do that?(inspired by kotlin)

How to dynamically set an Image object src in javascript and Vue

I’m trying to teach myself javascript and Vue.js. I was following the documentation on Vue’s site and modifying their demonstrations as an exercise. I wanted to change their looping directive example to dynamically add images to the list from a specified url. I can’t seem to get the image to show despite setting the image properties src field. I have verified that everything runs and the field is in fact getting set. I assume I must be misunderstanding something related to the DOM or ordering of events.

Thanks in advance.

HTML

<script src="https://unpkg.com/vue@next"></script>

<div id="list-rendering" class="demo">
  <input v-model="imgsrc"></input>
  <button v-on:click="setImage">  Set</button>
  <ol>
    <li v-for="todo in todos">
      {{ todo.text }} {{todo.image}}
    </li>
  </ol>
</div>

CSS

.demo {
  font-family: sans-serif;
  border: 1px solid #eee;
  border-radius: 2px;
  padding: 20px 30px;
  margin-top: 1em;
  margin-bottom: 40px;
  user-select: none;
  overflow-x: auto;
}

Javascript

const ListRenderingApp = {
  data() {
    return {
      todos: [
        { text: 'Learn JavaScript',
          image: new Image(16,16)},
        { text: 'Learn Vue',
          image: new Image(16, 16)},
        { text: 'Build something awesome',
          image: new Image(16, 16)}
      ],
      imgsrc: ""
    }
  },
  methods:{
    setImage(){
       this.todos.map(todo => todo.image.src = this.imgsrc)
    }
  }
}

Vue.createApp(ListRenderingApp).mount('#list-rendering')

Vue problem why it will not work in Windows 11 [closed]

Vue.js won’t work.

I’m trying code that used to work before, so the code isn’t the issue. None of the Vue.js seems to work either in Brave browser, or in Firefox.

I can’t seem to figure out what is the main problem here. I’ve tried several CDNs, I’ve tried several code examples.
I am using Windows 11.

Are there any settings I should take into account in the browser?

Or, maybe is the Anti-Virus scanner the problem? I’m using Norton for lack of a better one right now.

Are there any settings in Windows 11 I need to check?

What is a simple checklist I could follow to ensure that Vue.js works? Any installation steps I can repeat to have it function?

Thanks a bunch in advance… I really want to continue w/ my course.

async await axios post data with vue js, the data send is different between vue and postmant

i try to create data with vue js, but backend can not read the data and just send “undefined” to database, i try create data with postman, backend can read the data,

i see the data captured on backend, it turns out that there is a difference between the data sent by vue js end the data sent by postman

here is the data sent by postman

[Object: null prototype] { name: '6', email: '5', password: '3' }

and here is the data sent by vue js

[Object: null prototype] {
  '{"name":"2","email":"2","password":"2"}': ''
}

here is the script in vue js

<script>
  import axios from "axios";
  export default {
    name: 'AddUser',
    data(){
      return {
        model: {
          name: '',
          email: '',
          id_status: '',
          password: '',
        }
      };
    },
    methods: {
      async saveUser(){
        try{
          const response = await axios.post('http://localhost:8000/users',this.model);
          res.data.headers['Content-Type'];
          console.log(response);
        } catch (err){
          console.log(err);
        }
      }
    },
  };
</script>

and here is script in node js as backend

if(q.pathname == "/users" && req.method == "POST"){
        var body = '';
        req.on('data', function(data){
            body += data;
            if(body.length > 1e6)
                req.connection.destroy();
        });

        req.on('end', function(){
            var postData    = qs.parse(body);
            let name        = postData.name;
            let email       = postData.email;
            let id_status   = postData.id_status;
            let password    = postData.password;            
            let sql = `insert into users (name,email,id_status,password) values ('${name}','${email}','${id_status}','${password}')`
            console.log(postData)
            db.query(sql,(err, result) => {
                if (err) throw err;

                if(result.affectedRows == 1){
                    res.end(JSON.stringify({message: 'success'}));
                }else{
                    res.end(JSON.stringify({message: 'failed'}));
                }   
            });
        });

Why am I still getting an error with a DELETE request in Postman?

I’m kinda new to programming and I am trying to send a delete request to Postman but I keep getting this error in postman. Would anyone know how to fix this?

ERROR:

{
    "code": 79,
    "codeName": "UnknownReplWriteConcern",
    "errInfo": {
        "writeConcern": {
            "w": "majority;",
            "wtimeout": 0,
            "provenance": "clientSupplied"
        }
    },
    "result": {
        "n": 1,
        "opTime": {
            "ts": {
                "$timestamp": "7022899934215012355"
            },
            "t": 99
        },
        "electionId": "7fffffff0000000000000063",
        "ok": 1,
        "writeConcernError": {
            "code": 79,
            "codeName": "UnknownReplWriteConcern",
            "errmsg": "No write concern mode named 'majority;' found in replica set configuration",
            "errInfo": {
                "writeConcern": {
                    "w": "majority;",
                    "wtimeout": 0,
                    "provenance": "clientSupplied"
                }
            }
        },
        "$clusterTime": {
            "clusterTime": {
                "$timestamp": "7022899934215012355"
            },
            "signature": {
                "hash": "/gnrM/bYkyRYi4XXXmEnkaLJJpg=",
                "keyId": {
                    "low": 1,
                    "high": 1620408145,
                    "unsigned": false
                }
            }
        },
        "operationTime": {
            "$timestamp": "7022899934215012355"
        }
    }
}

NOW, the delete request is working properly as I can see the query selection being deleted when I send the delete request but I am still getting that error in postman. I tried using this solution https://stackoverflow.com/a/69779799/16216414 which was working fine when I used any other request in Postman. I tried checking my code for

posts.js:

const router = require("express").Router();
const User = require("../models/User");
const Post = require("../models/Post");

//CREATE POST
router.post("/", async (req, res) => {
  const newPost = new Post(req.body);
  try {
    const savedPost = await newPost.save();
    res.status(200).json(savedPost);
  } catch (err) {
    res.status(500).json(err);
  }
});

//UPDATE POST
router.put("/:id", async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);
    if (post.username === req.body.username) {
      try {
        const updatedPost = await Post.findByIdAndUpdate(
          req.params.id,
          {
            $set: req.body,
          },
          { new: true }
        );
        res.status(200).json(updatedPost);
      } catch(err) {
      res.status(500).json(err);
      }
    } else {
      res.status(401).json("You can only update your post.")
    }
  } catch(err) {
      res.status(500).json(err)
  }
});

//DELETE POST
router.delete("/:id", async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);
    if (post.username === req.body.username) {
      try {
        await post.delete();
        res.status(200).json("Post has been deleted...");
      } catch (err) {
        res.status(500).json(err);
      }
    } else {
      res.status(401).json("You can delete only your post!");
    }
  } catch (err) {
    res.status(500).json(err);
  }
});

//GET USER
router.get("/:id", async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);
    res.status(200).json(post);
  } catch (err) {
    res.status(500).json(err);
  }
});

module.exports = router;

How to detect (when trying to append a created element) if that element has been created once before with JavaScript

So I’m trying to build a gif/webm/png etc viewer, right now I’m creating elements to then set the file selected to that img (or if it is a webm file, then we’ll set it’s src to a video element)

Now I’m also building a hide button (the element I want to see if it’s already appended) to hide the image or video when it is clicked, so I want to create it… then append it when an image like a gif or png is chosen, but I have made a listener to detect if the file is a webm.

I also want to detect if the document already has the hide button, so therefore I can assign a hide button to either the img element or video separately element because as on my codepen
the hide button won’t work to hide the video when the img is created first then the video and so forth.

Basically I want to detect if the hide button has been appended before for the img element and/or video element (to prevent duplicates on the page) then delete it and create a new one that will read for the new video or img element.