Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
How to swap <div> elements by using "mouseover" event?
let wrapperSt = document.querySelector(".wrapper");

for(i=0; i<100; i++){
let divGroup = document.createElement('div');
wrapperSt.append(divGroup);
divGroup.className= 'pixel';
divGroup.textContent= '';
}

I've created the div element called "pixel" by using loop because, i need couple hundreds of them. (I'll use them as a little boxes that could change color)

But, i want these boxes ("pixel" div) to turn brown and sustain (style.backgroundColor ="brown";)

So, i created another div that will replace the previous div ("pixel").

let selectPx = document.getElementsByClassName("pixel");

selectPx.addEventListener("mouseover", function(){

let pxChange = createElement("div");
//This is where i got stuck!

})

I could not finish my code, i found it a bit complicated even if it is probably something very simple.

Any suggestions or piece of information would be very helpful. Thank you.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Not sure exactly what you are trying to do... I think you are trying to change the color of the div that your mouse is over? If so, you have a couple of issues with your code. Instead of adding the event listener to the list of divs, you need to add it to each one individually. Also, you should only need to change the background color of each element instead of creating a new one each time.

let selectPx = document.querySelectorAll(".pixel");

selectPx.forEach(pixel => {
  pixel.addEventListener("mouseover", () => {
    pixel.style.backgroundColor = "brown";
  });
});
about 4 years ago · Juan Pablo Isaza Report

0

I'm not sure why you have to create a new div inside the first one. In your code, when you trigger the mouseover event you can get the div under the mouse and apply the style to it:

let selectPx = document.getElementsByClassName("pixel");

selectPx.addEventListener("mouseover", function(evt){

    let divUnderMouse = evt.target;
    divUnderMouse.style.backgroundColor ="brown";

})

I haven't tried it but it should work

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!