0

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);
Richard Wilson
  • 297
  • 4
  • 17
Danesinhell
  • 25
  • 1
  • 5
  • You only set `divPresent` once, then never check it again. `divPresent` won’t magically change inside the function. Store the removed element in a variable and check its `isConnected` property. – Sebastian Simon Sep 19 '21 at 09:33
  • @SebastianSimon can you please go into more detail, I'm the very definition of a newbie when it comes to js – Danesinhell Sep 19 '21 at 09:36
  • The condition `divPresent == null` will never change when you run `run1` because you never set `divPresent` to something else. But instead of checking if the element exists by ID, simply check `if(div1.isConnected)` instead. Another problem: `document.body.remove(div1);` is wrong. It should either be `document.body.removeChild(div1);` or `div1.remove();`. – Sebastian Simon Sep 19 '21 at 09:40
  • @SebastianSimon thanks a lot, I will try to tinker with the function and see if it works – Danesinhell Sep 19 '21 at 09:46
  • Documentation: [`removeChild`](//developer.mozilla.org/docs/Web/API/Node/removeChild), [`remove`](//developer.mozilla.org/docs/Web/API/Element/remove), [`isConnected`](//developer.mozilla.org/docs/Web/API/Node/isConnected). Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Sep 19 '21 at 09:48

0 Answers0