dimanche 19 septembre 2021

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 [duplicate]

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);

Aucun commentaire:

Enregistrer un commentaire