En el siguiente código, estoy agregando una clase active cuando el usuario hace clic en li .
cuando hago document.querySelector(".active"); para seleccionar las li que contienen la clase activa el resultado es siempre la primera li que contiene la clase activa por defecto.
¿Cómo puedo obtener la clase activa cuando se agrega al hacer onclick en javascript?
let lis = document.querySelectorAll("li"); let lisArray = Array.from(lis); lisArray.forEach((li) => { li.addEventListener("click", function (e) { lisArray.forEach((ele) => { ele.classList.remove("active"); }); li.classList.add("active"); document.querySelector("body").style.backgroundColor = e.currentTarget.dataset.cont; window.localStorage.setItem("color", e.currentTarget.dataset.cont); }); }); if(window.localStorage.getItem("color")){ document.body.style.backgroundColor = localStorage.getItem("color"); }else{ document.body.style.backgroundColor = "white"; } let active = document.querySelector(".active"); console.log(active); * { margin: 0; padding: 0; list-style: none; box-sizing: border-box; } body { line-height: 1.6; font-size: 16px; min-height: 100vh; font-family: Arial; } ul { display: flex; align-items: center; gap: 10px; padding: 10px; background-color: #ddd; } ul li { border: 1px solid #f0f0f0; width: 20px; height: 20px; cursor: pointer; } ul li:first-of-type { background-color: white; opacity: 0.3; } ul li:first-of-type.active body { background-color: red; } ul li:nth-of-type(2) { background-color: red; opacity: 0.3; } ul li:nth-of-type(3) { background-color: green; opacity: 0.3; } ul li:nth-of-type(4) { background-color: deepskyblue; opacity: 0.3; } ul li.active, ul li:hover { opacity: 1; } <ul> <li class="active" data-cont="white"></li> <li data-cont="red"></li> <li data-cont="green"></li> <li data-cont="deepskyblue"></li> </ul>Establezca el elemento activo en la función de clic:
let lis = document.querySelectorAll("li"); let lisArray = Array.from(lis); let active; lisArray.forEach((li) => { li.addEventListener("click", function (e) { lisArray.forEach((ele) => { ele.classList.remove("active"); }); li.classList.add("active"); active = li; console.log(li); document.querySelector("body").style.backgroundColor = e.currentTarget.dataset.cont; window.localStorage.setItem("color", e.currentTarget.dataset.cont); }); }); if (window.localStorage.getItem("color")) { document.body.style.backgroundColor = localStorage.getItem("color"); } else { document.body.style.backgroundColor = "white"; } active = document.querySelector(".active"); console.log(active);