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

112
Vistas
Checking if an element is present in the dom at the click of one button, if element is not present add it, else remove it

to make my question clearer, I want to be able to check if an element is present in the dom at the click of a button, if that element isn't present then append it, else document.body.remove(element).

This is what I'm thinking: clicks button -> if the element isn't present it appears, else it disappears

this is my html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>

<button id="btn-1" onclick="run1()">show / remove</button>



<script type="text/javascript" src="basic.js"></script>
</body>
</html>

this is my javascript:

let div1 = document.createElement('div');
div1.className = 'exer-text';
div1.id = 'div1';
div1.id = 'special1';
let bold1 = document.createElement('b');
bold1.innerText = '2.';
let par1 = document.createElement('p');
par1.innerText = 'The answer to the question is ';
par1.append(bold1);
div1.append(par1);

const divPresent = document.getElementById('div1')

function run1() {
    if (divPresent == null) {
        document.body.append(div1);
    } 

    else {
        document.body.remove(div1);
    }
}


document.getElementById('btn-1').addEventListener('click', run1);
about 4 years ago · Juan Pablo Isaza
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