Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
¿Cómo hago para que los nodos HTML no se apilen?

Cuando se produce un evento de clic, aparece el contenido, pero se apila uno encima del otro. ¿Cómo hago para que el contenido HTML se muestre en una línea y no se apile? Es decir, ¿cómo puedo obtenerlo solo una vez después de que ocurra un nuevo evento de clic?

 function colorGenerator(e) { const r = Math.floor(Math.random() * 255) + 1; const g = Math.floor(Math.random() * 255) + 1; const b = Math.floor(Math.random() * 255) + 1; document.body.style.backgroundColor = `rgb(${r}, ${g}, ${b})`; const p = document.createElement('p'); const content = p.innerHTML = `rgb(${r}, ${g}, ${b})`; document.body.appendChild(p); //e.preventDefault() }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Background Color Generator</title> </head> <body> <button type="submit" onclick="colorGenerator()">Click Me to Change Color</button> </body> </html>

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

No agregue un nuevo elemento, innerHTML al HTML interno de un elemento existente para reemplazarlo.

 function colorGenerator(e) { const r = Math.floor(Math.random() * 255) + 1; const g = Math.floor(Math.random() * 255) + 1; const b = Math.floor(Math.random() * 255) + 1; document.body.style.backgroundColor = `rgb(${r}, ${g}, ${b})`; const p = document.getElementById('output'); p.innerHTML = `rgb(${r}, ${g}, ${b})`; }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Background Color Generator</title> </head> <body> <button type="submit" onclick="colorGenerator()">Click Me to Change Color</button> <p id="output"></p> </body> </html>

about 4 years ago · Juan Pablo Isaza Denunciar

0

tienes que hacer una cosa en cada función

1- generas color 2- agregas nodo a DOM

cada vez que hace clic en el botón, ejecuta colorGenerator y agrega un nuevo elemento al dom.

aquí algún ejemplo:

 const p = document.createElement('p'); p.setAttribute("id", "theP"); document.body.appendChild(p); function colorGenerator(e) { const r = Math.floor(Math.random() * 255) + 1; const g = Math.floor(Math.random() * 255) + 1; const b = Math.floor(Math.random() * 255) + 1; return `rgb(${r}, ${g}, ${b})`; } function changeColor (e) { var color = colorGenerator(e) document.body.style.backgroundColor = color; p.innerHTML = color; }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Background Color Generator</title> </head> <body> <button type="submit" onclick="changeColor()">Click Me to Change Color</button> </body> </html>

about 4 years ago · Juan Pablo Isaza Denunciar

0

  1. Use replaceWith() para reemplazar un elemento anterior con uno recién creado
  2. No use el atributo onclick ( lea aquí por qué )
  3. Puede usar un bucle en lugar de repetir tres veces sus cosas de generación de números aleatorios.

 const button = document.querySelector('button[type="submit"]'); generateColor = (e) => { e.preventDefault(); // Check for the existing element const existing = document.querySelector('p'); // Map over a range to avoid repeating yourself const [r, g, b] = [...Array(3).keys()].map(() => Math.floor(Math.random() * 255) + 1); const color = `rgb(${r}, ${g}, ${b})`; document.body.style.backgroundColor = color; const p = document.createElement('p'); p.textContent = color; // If ap tag already exists, replace it with new one if (existing) return existing.replaceWith(p); // Otherwise, append new one to the body (only happens on) // first click document.body.appendChild(p); }; // Use eventlistener instead of "onclick" attribute button.addEventListener('click', generateColor);
 <body> <button type="submit">Click Me to Change Color</button> </body>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda